Currying breaks down a function that receives multiple arguments into a series of functions that each receive part of the arguments.
Named after Haskell Curry, if we have f::(x, y) -> z, when curried we get curry(f) :: x -> y -> z.
ES6 Implementation
let curry1 = f => (a) => f(a);
let curry2 = f => (...a) => (...b) => f(...a, ...b);
let curry3 = f => (...a) => (...b) => (...c) => f(...a, ...b, ...c);
## nCurry for Any Arity
javascript
let nCurry = n => (f, ...args) => {
return function(...nargs) {
let combinedArgs = args.concat(nargs);
if (combinedArgs.length < n) {
combinedArgs.unshift(f);
return nCurry(n).apply(null, combinedArgs);
}
return f.apply(null, combinedArgs);
};
};
// Usage: nCurry(4)(listify)(1)(2)(3)(4); // [1,2,3,4]
Hope you enjoyed your curry! ๐
#javascript#es6#functional
About Hemanth HM
Hemanth HM is a Sr. Machine Learning Manager at PayPal, Google Developer Expert, TC39 delegate, FOSS advocate, and community leader with a passion for programming, AI, and open-source contributions.