Skip to content

Instantly share code, notes, and snippets.

@phatnguyenuit
Last active September 16, 2020 02:24
Show Gist options
  • Save phatnguyenuit/732355617a30f38c77f9912ed285b636 to your computer and use it in GitHub Desktop.
Save phatnguyenuit/732355617a30f38c77f9912ed285b636 to your computer and use it in GitHub Desktop.
JavaScript composition
/**
* 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)));
@phatnguyenuit
Copy link
Author

TODO: Check case multiple input params

@phatnguyenuit
Copy link
Author

✔️ Done

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment