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.

Screen Shot 2017-10-13 at 6.45.33 AM.png

Another way of looking at it is like this. Here is a regular dragon function.

Screen Shot 2017-10-13 at 6.47.22 AM.png

And here is the curried version of the same function.

Screen Shot 2017-10-13 at 6.47.43 AM.png

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.

Screen Shot 2017-10-13 at 6.49.45 AM.png

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.

Screen Shot 2017-10-13 at 6.53.54 AM.png

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.

Screen Shot 2017-10-13 at 6.56.32 AM.png

Why is currying handy

Let’s say we start off with something like this, and we want to improve it with currying.

Screen Shot 2017-10-13 at 6.58.18 AM.png

Let’s import lodash, and curry has element.

Screen Shot 2017-10-13 at 7.00.46 AM.png

Then if you remove the wrapping function you can just do this

Screen Shot 2017-10-13 at 7.25.35 AM.png

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.

Advertisement