Here's a simpler way to do curry functions in Javascript.
We have previously seen currying in Javascript. A simple form and application of that concept is demonstrated below -
const addThem = add.curry(2);
const addTotal = addThem(1);
console.log("addTotal: ", addTotal); // 3
Alternatively, we could avoid an external function or library and curry using bindings ..
function add(x) {
return function(y) {
return y + x;
};
}
const addEm = add(1);
console.log(addEm(2)); // 3
But, there is a simpler way to get the same result.
We just use arrow functions to collect arguments at different times.
const add = x => y => x + y;
const addEm = add(1);
console.log(addEm(2)); // 3
We can make the code more readable with a different notation to do the actual curry -
const add = x => y => x + y;
console.log(add(1)(2)); // 3
Of course, you have to rely back on the previously provided example if you don’t have all arguments in one go.
Top comments (0)