Last active
January 3, 2024 16:47
-
-
Save WaldoJeffers/905e14d03f4283599bac753f73b7716b to your computer and use it in GitHub Desktop.
JavaScript one-line compose (ES6)
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) => fns.reduce((f, g) => (...args) => f(g(...args))) | |
// Usage : compose functions right to left | |
// compose(minus8, add10, multiply10)(4) === 42 | |
// | |
// The resulting function can accept as many arguments as the first function does | |
// compose(add2, multiply)(4, 10) === 42 |
Very cool piece of code - I learned a lot from it. Thank you very much for the explanation as well!
I decided to test the expanded version, works like a charm!
const multiply = (x,y) => x*y
const add6 = (x) => x+6
const minus3 = (x) => x-3
// compose(add6, minus3, multiply)(3,10)
const result = ((...arg1) => ((...arg2) => add6(minus3(...arg2)))(multiply(...arg1)))(3,10)
console.log(result) // === 33
You could probably use reduceRight
with the additional ...args
spread operator
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thanks your elaborate