Skip to content

Instantly share code, notes, and snippets.

@trevor-atlas
Forked from JamieMason/es6-compose.md
Last active December 9, 2017 00:51
Show Gist options
  • Save trevor-atlas/474aa8fb40c453ab2ec00bce013d043a to your computer and use it in GitHub Desktop.
Save trevor-atlas/474aa8fb40c453ab2ec00bce013d043a to your computer and use it in GitHub Desktop.
ES6 JavaScript compose function

ES6 JavaScript Compose Function

Definition

const compose = (...fns) => fns.reduce((f, g) => (...args) => f(g(...args)));
const pipe = (...fns) => compose.apply(compose, fns.reverse());

Example

Create the function, composed of three others:

const example = compose(
  val => { console.log(1); return `1<${val}>`; },
  val => { console.log(2); return `2<${val}>`; },
  val => { console.log(3); return `3<${val}>`; }
);

const example2 = pipe(
  val => { console.log(1); return `1<${val}>`; },
  val => { console.log(2); return `2<${val}>`; },
  val => { console.log(3); return `3<${val}>`; }
)

Call the functions:

console.log("Compose");
console.log(example('hello'));

console.log("Pipe");
console.log(example2('hello'));

Console output is:

Compose
3
2
1
"1<2<3<hello>>>"

Pipe
1
2
3
"3<2<1<hello>>>"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment