Skip to content

Instantly share code, notes, and snippets.

@jmakeig
Last active July 9, 2019 20:51
Show Gist options
  • Save jmakeig/a36b9bec7e75afdf6cf22b5794e28487 to your computer and use it in GitHub Desktop.
Save jmakeig/a36b9bec7e75afdf6cf22b5794e28487 to your computer and use it in GitHub Desktop.
Function composition in JavaScript
// https://www.codementor.io/michelre/use-function-composition-in-javascript-gkmxos5mj
function compose(...functions) {
return args => functions.reduceRight((arg, fn) => fn(arg), args);
}
const cntk = {
c1(input, options = {}) {
// console.log('c1', input, options);
return 'c1: ' + input;
},
c2(input, options = {}) {
// console.log('c2', input, options);
return 'c2: ' + input;
}
};
compose(
input => cntk.c1(input, { foo: true }), // partial application to pass in static options
cntk.c2
)('asdf'); // 'asdf' is input to the first function
// 'c1: c2: asdf'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment