Continuing my following of mpj’s series.
Currying is when a function, instead of taking all arguments at once, takes the first one and returns a new function, that takes the second one and returns a new function, which takes the third one and so on until all the arguments have been fulfilled.
Here it is in lodash.
Another way of looking at it is like this. Here is a regular dragon function.
And here is the curried version of the same function.
In this curried version dragon
is a function, that takes name as an argument, and returns a function that takes size as an argument, that returns another function that takes element as an argument, which in turn finally uses all three arguments.
And you call it, like this.
This may look strange at first, but it’s not that bad. It’s just three method calls, all combined (or curried) together where a method keeps getting returned, and you simply chain the argument parameters. It does look strange. But that’s how it works. It’s just a chain of functions.
The idea with curries is that you can pass your function through your application, decorating it up and adding functions to it as you go.
For example we might break out various functions and call them in a more incremental manor like this.
Now some tools/libraries, like lodash, help make your regular JS functions curriable. For example we have have left our dragon function like this. And then called it with lodash like this.
Why is currying handy
Let’s say we start off with something like this, and we want to improve it with currying.
Let’s import lodash, and curry has element.
Then if you remove the wrapping function you can just do this
What making hasElement
curryable does it is means hasElement
can return a new function, which takes a new argument which can be called from filter
.
It’s still a bit weird. And I am still getting my head wrapped around it. But it looks like this could be handy for chaining function calls together, while passing arguments in just-in-time.
Leave a Reply