Skip to content

Instantly share code, notes, and snippets.

@WaldoJeffers
Last active January 3, 2024 16:47
Show Gist options
  • Save WaldoJeffers/905e14d03f4283599bac753f73b7716b to your computer and use it in GitHub Desktop.
Save WaldoJeffers/905e14d03f4283599bac753f73b7716b to your computer and use it in GitHub Desktop.
JavaScript one-line compose (ES6)
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
@sponia-joker
Copy link

thanks your elaborate

@juliobetta
Copy link

juliobetta commented Feb 22, 2018

tenor 1

@ademarest
Copy link

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

@briancodes
Copy link

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