Skip to content

Instantly share code, notes, and snippets.

@beaucharman
Last active January 19, 2017 04:33
Show Gist options
  • Save beaucharman/d7aa767f432ce2474e47ef41cf617f74 to your computer and use it in GitHub Desktop.
Save beaucharman/d7aa767f432ce2474e47ef41cf617f74 to your computer and use it in GitHub Desktop.
Returns a function that composes a series of methods together, passing the return value of each from left to right (First method can take multiple arguments)
const compose = (...functions) => (...start) => (
functions.reduce((result, f) => (
(typeof result === 'object') ? f(...result) : f(result)
), start)
)
/**
* Usage
*/
const add = (a, b = 4) => a + b
const sub1 = (a) => a - 1
const mul2 = (a) => a * 2
const div2 = (a) => a / 2
const addSub1Mul2Div2 = compose(add, sub1, mul2, div2)
console.log(addSub1Mul2Div2(1, 3))
// -> 3
// why? 'cause div2(mul2(sub1(add(1, 3)))) looks gross
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment