Last active
December 16, 2020 06:34
-
-
Save renaudtertrais/fbb1a78d495bd72b8b318fb7368644e2 to your computer and use it in GitHub Desktop.
Simple ES6 compose & pipe function
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
const compose = (...fns) => (...args) => { | |
return fns.slice(0, -1).reduceRight((res, fn) => fn(res), | |
fns[fns.length -1].apply(null,args) | |
); | |
}; | |
const pipe = (f1, ...fns) => (...args) => { | |
return fns.reduce((res, fn) => fn(res), f1.apply(null,args)); | |
}; | |
// example | |
const add2 = (n) => n + 2; | |
const times2 = (n) => n * 2; | |
const times2add2 = compose(add2, times2); | |
const add2tiems2 = pipe(add2, times2); | |
const add6 = compose(add2, add2, add2); | |
times2add2(2); // 6 | |
add2tiems2(2); // 8 | |
add6(2); // 8 |
You can replace f1.apply(null,args) with f1(...args)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks nice work