Home > Net >  JavaScript – Modularize for-loop of a method
JavaScript – Modularize for-loop of a method

Time:12-28

I have a function like this:

function makeSummary(people){
    const myList = []
    for (int i = 0; i < people.length; i  ){
          myList.push({
            fullName: person.firstName   " "   person.lastName,
            title: person.title,
          })
    }
    return myList
}

which, given a list of people, constructs a slightly modified version of the list.

Is there any way I can pass the object that's constructed on any step of the for loop as a parameter?

I'd like to modularize this function for further reuse (this is just an example, my real code is a lot bigger, so it makes much more sense there, but the scenario is the same).

So, I'd like there to be an argument where I pass something like:

{
     fullName: person.firstName   " "   person.lastName,
     title: person.title,
}

and for the next function call, I could pass:

{
     fullName: person.firstName   " "   person.lastName,
     description: person.description,
}

and the method should know that that's the object that should be added at every step in the for-loop.

Is there any way to achieve this?

Thanks!

CodePudding user response:

You can simply move your hard coding of the object from makeSummary function, instead pass it as parameter. which will give you flexibility of defining helper function as per your need.

function makeSummary(people, helper){
    const myList = []
    for (int i = 0; i < people.length; i  ){
          myList.push(helper(people[i])
    }
    return myList
}


function helper1(person){
  return {
      fullName: person.firstName   " "   person.lastName,
      title: person.title,
  }
}

function helper2(person){
  return {
      fullName: person.firstName   " "   person.lastName,
      description: person.description,
  }
}

//call it like this
makeSummary(people, helper1)
makeSummary(people, helper2)
  • Related