When working on some filtering and sorting functionality, there is something wished I would have learned much earlier in my career. Before that point I didn’t really understand what higher order functions were or why it would be useful to return a function from another function. So I hope that this might help someone find out about this a bit sooner than I did.
Why would you return a function from a functioin. Or rather what does this even do, and why is it useful:
const someFunction = (prop1) => (prop2) => {
...
}
Problem:
Working with the array
methods filter
and sort
I quickly hit a wall where I wanted to pass custom arguments into my sorting function. But when you try:
const someFunction = (item, customProp) => {
...
}
someArray.filter(someFunction(???, 'custom arg'));
that doesn’t work because you are actually caling the function someFunction
when you are adding the ()
at the end. The method needs a function reference.
So the function needs to look like this:
const someFunction = (item) => {
...
}
someArray.filter(someFunction);
or inline:
someArray.filter( (item) => {
...
})
But doing it that way means that you can’t really pass any othe parameters to the filter function.
In my usecase I wanted to add an option to filter objects based on different props.
You would be able to use .bind()
, but in my opinion that is harder to understand and harder to maintain with multiple people on the team.
Solutoin:
The solution for me were functions that return other functoins.
If we look back at what we actually need to pass to the filter method, its a function that will be passed one prop, being the individual item in the array.
So why not make the return statement of our sorting function exactly that:
const someFunctioin = (customProp) => {
return (item) => {
// do something with the custom prop and item here
...
}
}
or with a bit cleaner syntax:
const someFunction = (customProp) => (item) => {
// do something with the custom prop and item here
...
}
with this we can access the customProp
from inside the returned funcition. And because what we are returning is actually a function refference, as far as the filter
or sort
methods are concerned, we are just passiing it a function to sort.
So the final code I came up with:
const byProp = (searchTerm, propName) => element => {
if (element[propName] === undefined) {
throw new Error(`The prop "${propName}" doesn't exist`);
}
return searchTerm === element[propName];
};
And with it II am now able to use this function for filtering objects based on the contents of one of their props.
/*
* filter an array named people for the ones that have
* a prop called "name" with the value of "Harry"
*/
people.filter( byProp( "Harry", "name" ) );
One Reply to “What are higher order functions?”
Nice explanation! Thanks for sharing 😁