Last active
July 9, 2019 20:51
-
-
Save jmakeig/a36b9bec7e75afdf6cf22b5794e28487 to your computer and use it in GitHub Desktop.
Function composition in JavaScript
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
// 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