MisterniceGuy
MisterniceGuy

Reputation: 1786

How can I reuse function by making it more flexible

I am trying to build a function in my NodeJs Api which will return objects in an array that meet certain criteria. In this case I am using findIndex to do this. My question is to be able to reuse the function is there a way to pass in the values like [phones] in data.phones.findIndex so that if i would want emails i could just pass in emails without having to create a new function ? Further more can i pass in the field like [type] in the item.type ? As for the phones part I know I could call it like this

getWorkPhone(myObj.phones, 'Work')

and remove the phones and make it data.findIndex . Final Part would be how can i get all indexes should there be more then one since findIndex returns only the first match ?

 const getWorkPhone = (data, myValue) => {
    const index = data.phones.findIndex(item => item.type === myValue && item.dflt === true)
    console.log(index)
    console.log(data.phones[index].number)
  }

Upvotes: 0

Views: 75

Answers (1)

Evert
Evert

Reputation: 99523

I think you need filter to get a list of all 'things' in an array that meet a certain condition.

So perhaps, this is a nice syntax:

const workNumbers = numbers.filter(phoneFilter('work'));

Then the responsibility of your phoneFilter function is to return a function that works with filter.

function phoneFilter(type) {

   return (item) => item.type === type;

}

Of course, this is not that different from doing everything in-line, but it does add some nice semantic meaning. Doing everything without helper functions looks like this (which I think is still pretty obvious/readable):

const workNumbers = numbers.filter(item => item.type === 'work');

A third way is to define a function that does both the .filter() invocation, and the filtering itself, but I think it doesn't compose as nicely:

function myPhoneFilter(numbers, type) {
  return numbers.filter(item => item.type === type);
}

const workNumbers = myPhoneFilter(numbers, 'work');

For simple use-cases such as this, I would probably not even bother writing helper functions, because the the inline version is already so obvious:

Upvotes: 2

Related Questions