Functional programming in JavaScript: Currying
What is currying?
Currying is one of those concept that is easier to show than to define but let’s give it a try
In functional programming, currying is the process of spreading multiple arguments of a function across a sequence of nested functions.
Now that I attempted to give a definition let’s see what it actually means in practice.
The starting point for currying is a function that accepts multiple arguments.
Here is an add
function that takes 3 arguments and sums them.
|
|
Nothing too special so far but now let’s try creating a curried version of it:
|
|
As you can see we moved each argument to a dedicated function and what we get is a structure where each function returns another function that you are supposed to call passing the next argument until you reach the end.
Why would I need it?
Currying is particularly helpful when you have to call a function with the same arguments over and over again.
If we see that we call the add
function passing the same a
and b
many times, I could assign the first 2 functions of the curried version to a variable and then call it passing only the third parameter.
|
|
How to create curried functions
Of course we could turn each function into a curried version in the same way we did it earlier but if wouldn’t be very efficient.
What we want is a function that handles if for us without having to worry about the implementation the function we want to “currify”.
Although there are several libraries that provides such functionality, see Lodash curry, here is how you can do it yourself.
|
|
The curry
function creates a recursive curried
function that, when the passed args length is equal or greater than the original function (fn
) args, it calls fn
passing the args
using fn.apply(this, args)
.
Otherwise, instead of calling fn
, another wrapper is returned, that will re-apply the curried function passing the previous arguments along with the new ones.
Now, we can pass the original add
to our new curry function and use the curried result.
|
|
In this tutorial, we have examined the currying transformation process in JavaScript.