DEV Community

Cover image for Function currying for the dynamic length of params i.e Implementing Add(1)(2)(3).....(n)()
Prashant Andani
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:

// 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)

Collapse
 
bornik profile image
Nikita Borisov

Very elegant solution!
Do you think it is possible to omit () in the end?