Currying refers to the process of transforming a function with multiple arities into the same function with less arity. The curried effect is achieved by binding some of the arguments to the first function to invoke so that those values are fixed for the next invocation. Hereโs an example of what a curried function looks like:
// add(2)(3);
and the function definition is
function add(a) {
return function(b) {
return a + b;
}
}
The above solution works for the currying for a function with two params
How would we achieve if there are more dynamic no. of params
i.e add(2)(3)(4)(5)....(n)()
Let's write a generic add
function that takes n
no. of params.
function add(a) {
return function(b) {
return b ? add(a + b) : a;
}
}
๐ One-liner solution with an ES6 arrow function
const add = a => b => b ? add(a + b) : a;
๐ ๐๐ป ๐๐ผ ๐๐ฝ ๐๐พ ๐๐ฟ
Top comments (1)
Very elegant solution!
Do you think it is possible to omit () in the end?