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

7 1

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; 

πŸ™Œ πŸ™ŒπŸ» πŸ™ŒπŸΌ πŸ™ŒπŸ½ πŸ™ŒπŸΎ πŸ™ŒπŸΏ

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (1)

Collapse
 
bornik profile image
Nikita Borisov β€’

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

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay