Skip to content
Advertisement

Currying a function that takes infinite arguments

Using ES5, how do you curry a function that takes infinite arguments.

JavaScript

The function above takes only three arguments but we want our curried version to be able to take infinite arguments.

Hence, of all the following test cases should pass:

JavaScript

Here is the solution that I came up with:

JavaScript

However, I have been told that it’s not very “functional” in style.

Advertisement

Answer

Part of the reason your add function is not very “functional” is because it is attempting to do more than just add up numbers passed to it. It would be confusing for other developers to look at your code, see an add function, and when they call it, get a function returned to them instead of the sum.

For example:

JavaScript

The functional approach

The functional approach would be to create a function that allows you to curry any other functions, and simplify your add function:

JavaScript

Now, if you want to curry this function, you would just do:

JavaScript

If I still want to add 1, 2, 3 up I can just do:

JavaScript

Continuing the functional approach

This code is now becoming reusable from everywhere.

You can use that curry function to make other curried function references without any additional hassle.

Sticking with the math theme, lets say we had a multiply function that multiplied all numbers passed to it:

JavaScript

This functional currying approach allows you take that approach to any function, not just mathematical ones. Although the supplied curry function does not support all edge cases, it offers a functional, simple solution to your problem that can easily be built upon.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement