Infinite Currying In Javascript

Infinite Currying in Javascript

We know that javascript is a very interesting language with a lot of quirks. Although we have discussed earlier that currying is a concept not tied to javascript only and it generally helps to transform a function with multiple arguments into a series of nesting functions

In this article, we will generally be talking about Infinite Currying in javascript. So let us now take a scenario where we have a function sum where we can pass arguments like this sum(1)(2)(3)(4)….(n) and it can go onto any number. The sum function should generally give me a sum of all the numbers. In this case, it should probably give me the output as 10.

This is a very famous interview question and whenever you see a question like this in an interview then try to understand what the function is trying to achieve. In javascript, we know that functions are first-class objects or we can say that function behaves very similarly to a variable or an object in javascript. So whenever you face such type of question in an interview as discussed above try to break your problem into simple parts.

Now let us just solve it for a smaller problem. So take it as sum(1)(2) instead of sum(1)(2)(3)(4)  for now. Let us solve it now with the code given below:

Example :

Infinite Currying in Javascript

Output:

Infinite currying in javascript output

In the above example, we have taken sum as a function that takes an argument and this sum function will again return us a function that will take the argument as b. And now the below function which takes the argument will now return me the sum of a and b. This will generally give us the output as 3 to console.

This is generally a smaller problem but suppose we have something like sum(1)(2)(3) then we have to return another function which should take c as an argument. In this, we can see a clear pattern and we want to solve this question recursively.

Example:

Infinite Currying in Javascript Example

Output:

infinite currying output

In the above code, we are taking a sum function which takes an argument a. Now, this sum function will return another function which will take an argument b. And now we are checking whether b exists or not. If the value of b exists then we are returning the sum function again and passing the argument as the sum of a+b. Otherwise, we are just returning the value of an as we are considering a case where the value of b will be an empty argument.

When we  console.log(sum(1)(2)(3)(4)()) then the output to the console will be 10 as we have made the function sum function very smart above which helps us to achieve the sum of the pattern given below.

Video Explanation of the Topic

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Stay Connected

0FansLike
3,499FollowersFollow
19,400SubscribersSubscribe
- Advertisement -spot_img

Latest Articles