For more tips like this, sign up to the weekly newsletter!
Use higher-order functions for reusability
When you need a functionality in multiple places, you can move it out to a function. For example, let's have one that adds 5 to each user object's score:
const users = [
{name: "user1", score: 15},...
];
const add5 = (user) => {
return Object.assign({}, user, {score: user.score + 5});
}
console.log(users.map(add5)); // score: 20
Then later, when you need some further customizability, you add new parameters:
const addScore = (user, score) => {
return Object.assign({}, user, {score: user.score + score});
}
console.log(users.map((user) => addScore(user, 5))); // score: 20
But with this structure, the original function's signature is effectively lost. You can see this with the call to map
.
You can use higher order function to make more generalized versions of existing functions. Instead of passing all parameters at once, pass them in batches.
With a function that gets the score first and the user object last, the signature of our first function is preserved, while also supporting parameterization:
const addScore = (score) => (user) => {
return Object.assign({}, user, {score: user.score + score});
}
const add5 = addScore(5);
console.log(users.map(add5)); // score: 20