Infinite Currying in JavaScript

A tutorial on how to implement infinite currying in JavaScript.

Well, one fine day I was giving an interview for the frontend developer position and during the whole discussion, I came across a problem in which I had to develop a function that looked like this.

console.log(sum(1)(2)(3)(4)(5)(6)());

Basically, this is a function that could sum n numbers. The first thing that came to mind was that “it is currying”. So I tried to make a hard-coded solution that will return a series of functions waiting for the following input.

function sum(a) {
  return function (b) {
    return function (c) {
      return a + b + c;
    };
  };
}
console.log(sum(1)(2)(3)());

But the code looks ugly and it is hard coded. It can not work for more arguments. It can only serve the purpose of 3 arguments. So, how can we make this code more generalised and useful for a programmer, and more importantly how to make the interviewer happy?

So here comes one more concept that saves us from doing repetitive tasks .

Recursion

Think about how we can implement recursion in this problem. Firstly, we will have to think of the base case for our recursion to end.

sum(1)(2)(3)(4)(5)(6)……()

Base Case

As we can see here that this function will go on till a particular condition and what this particular condition is? We will break the recursion when we see that there is no more argument to the function call. We will return the sum when we make the call with no more arguments i.e. on the last ().

Otherwise, we will keep returning a function that will expect us to make a call with one more argument.

Code

Recursive Currying:

function sum(a) {
  return function (b) {
    if (!b) {
      return a;
    }
    return sum(a + b);
  };
}
console.log(sum(1)(2)(3)(4)(5)(6)()); //21

Here we are returning the sum function again if argument b is present. Let’s imagine the recursion for inputs sum(1)(2)(3)().

1 — — — returns sum(1)

2 — — — returns sum(1+2)

3 — — — returns sum(1+2+3)

And for the last call, we don't have argument b. So our function returns 1+2+3. In the first 3 calls, we return the inner function which can accommodate one more argument.

If this seems difficult to you just don’t worry because I wasn't able to come up with this solution on the first try. It took me several minutes and hints from the interviewer. I’ll link a video for much more clarification on this topic because it’s difficult to explain things in writing.

I will also recommend this channel for each and everyone as he posts really useful content on his channel.

https://youtu.be/eGE-tFalwpA

Here in this post, we learnt about infinite currying and its implementation in JavaScript.

Enjoyed this article?

Share it with your network to help others discover it

Continue Learning

Discover more articles on similar topics