Last active
May 15, 2016 02:02
-
-
Save griffinmichl/c1a60012e1da0d678bed499aa3e649a4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ES6 compose | |
const compose = (...funcs) => | |
x => funcs.reduceRight((acc, func) => func(acc), x); | |
// ES5 equivelant | |
var compose = function(){ | |
var args = Array.prototype.slice.call(arguments); | |
return function(val){ | |
return args.reduceRight(function(memo, fn){ | |
return fn(memo); | |
}, val); | |
}; | |
}; | |
// ES6 version explaination | |
const compose // define a constant veriable called compose | |
= (...funcs) => // compose is a function that takes an arbitrary number of args and puts them in an array called funcs | |
x => // compose returns a function | |
funcs.reduceRight((acc, func) => func(acc), x) // ... | |
// when the function returned from compose is invoked with x, it will set x as the initial value to reduceRight. | |
// reduceRight will iterate right-to-left over the original array of functions. It will apply each function to | |
// the accumulator, then the result of each function invokation will be set as the new accumulator | |
// Example | |
const add1 = a => a + 1; // take a number, add 1 to it, and return | |
const mult5 = a => 5 * a; // take a number, multiply it by 5, and return | |
const add1ThenMult5 = compose(mult5, add1); | |
// add1ThenMult5 = x => [mult5, add1].reduceRight((acc, func) => func(acc), x) | |
add1ThenMult5(5) | |
// first we do add1(5) and set the result of that operation (6) as the new accumulator | |
// then we do mult5(6) and return that value (30) as our result, since we reached the beginning of our array |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment