Last active
September 16, 2020 02:24
-
-
Save phatnguyenuit/732355617a30f38c77f9912ed285b636 to your computer and use it in GitHub Desktop.
JavaScript composition
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
/** | |
* Compose a list of function from right to left | |
* @param {...Function} funcs | |
*/ | |
const compose = (...funcs) => { | |
return funcs.reduceRight((prevFunc, currentFunc) => (...args) => { | |
const params = prevFunc.apply(null, args); | |
return currentFunc.apply(null, Array.isArray(params) ? params : [params]); | |
}); | |
}; | |
const plus = (x) => (y) => x + y; | |
const multiply = (x) => (y) => x * y; | |
// plus(3)(multiply(2)(10)); | |
const composedFunc = compose(plus(3), multiply(2)); | |
console.log(composedFunc(10)); | |
console.log(plus(3)(multiply(2)(10))); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
TODO: Check case multiple input params