-
-
Save JamieDixon/c74526cf427d8f5836789bbae7b25499 to your computer and use it in GitHub Desktop.
// A contrived compose function. | |
const compose = (f1, f2) => (...args) => f1(f2(...args)); | |
// These functions are curried. Instead of the usual (a, b) => a + b, we're supplying each parameter individually | |
// and then returning a function that takes the next param. | |
// This is currying. We're taking a function that normally has 2 params, and turning it into a function that takes 1 param, | |
// then returns another function expecting the second param. | |
const add = a => b => a + b; | |
const multiply = a => b => a * b; | |
// Let's build a new function by composing the above 2 and partially applying some values to them | |
const addTwoThenDouble = compose(multiply(2), add(2)); | |
// Running this over the value 10 looks like this | |
addTwoThenDouble(10) // outputs 24 |
One of the benefits we get is the ability to supply some of the parameters up-front while leaving the rest for later.
This helps us build new functions that make use of other functions like this:
const add = a => b => a + b;
const addTwo = add(2);
const addTen = add(10);
addTwo(5) // 7
addTen(90) // 100
We get this nice ability to supply some of the parameters up-front and what we get back is a new function ready to accept the next parameter.
If we weren't using arrow functions we might write it like this:
function add(a) {
return function(b) {
return a + b;
}
}
With regard to
const addTwoThenDouble = compose(multiply(2), add(2));
The reason this works is because compose
gives us a new function that is the combination (composition) of add(2)
(which is returning a function accepting b
) and multiply(2)
(which is also a function accepting b
).
When we call addTwoThenDouble(10)
we're firstly passing 10
to the function returned from add(2)
(10 is our b
value) so we get 12
(10 + 2). Then that value is being passed to the function returned by multiply(2)
. So now 12
is our b
value and 12 * 2
gets us our 24
.
This is lovely. What is the point of it over declaring something like:
?
To be honest, I don't see exactly how
addTwoThenDouble(10)
works to get 24