Prashant Andani

Posted on

# Function currying for the dynamic length of params i.e Implementing Add(1)(2)(3).....(n)()

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:

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

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;
``````

π ππ» ππΌ ππ½ ππΎ ππΏ