Currying And Partial

Functions are pretty versatile things.

Check this out:

var add_three = (a) => (b) => (c) => a + b + c  
console.log(add_three(1)(2)(3))  

As you might expect, this prints 6.

But what's up with (1)(2)(3)?

Well... add_three is 3 functions smooshed together.

The first function takes one argument, a, and returns another function (b) => (c) => a + b + c.

This function takes one argument, b, and returns another function (c) => a + b + c. Since this inner-most function has access to the outer variables a and b, it all works.

The (1)(2)(3) thing works pretty much like chaining, but instead of immediately calling a method on a returned object, we're immediately calling the returned function.

check this out:

var add_two_more_to_5 = add_three(5)  
console.log(add_two_more_to_5(1)(4))  

add_two_more_to_5 returns a function that is equivalent to (b) => (c) => 5 + b + c.

For more examples of these kinds of shenanigans

var add_to_12 = add_two_more_to_5(7)  
var add_to_2 = add_three(1)(1)  

This whole thing, the idea that you keep adding parameters to a function until you get an actual return value, is called currying.

And what I've shown you so far isn't the only way to do it.

Just in case you happen to find yourself coding in ES5 (that's what you'll have to write if you're writing code for a browser with no transpiler (more about those later)) with no access to arrow functions, you can always used bind:

var mul4 = function (a, b, c, d) {  
    return a * b * c * d
}

var mul3 = mul4.bind(null, 1)

console.log(mul3(2, 2, 3))  

This doesn't work as nicely, so I'd recommend using partial from lodash:

var mul2 = _.partial(mul4, _, 1, _, 1)  
console.log(mul2(3, 3))  

The cool thing about partial is that it lets you put place-holders for arguments. This way you don't have to worry about writing your functions with the right order.

Looking for a software developer?