Skip to content

Instantly share code, notes, and snippets.

@frentsel
Forked from JamieMason/es6-compose.md
Last active December 10, 2018 17:38
Show Gist options
  • Save frentsel/43c27fbe51d9525c3d2f9e785cbf49e5 to your computer and use it in GitHub Desktop.
Save frentsel/43c27fbe51d9525c3d2f9e785cbf49e5 to your computer and use it in GitHub Desktop.
ES6 JavaScript compose function

ES6 JavaScript Compose Function

Definition

const compose = (...fns) =>
  fns.reduce((prevFn, nextFn) =>
    (...args) => prevFn(nextFn(...args)),
    (value) => value);

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}>`; }
);

Call the function:

console.log(example('Hello', 'World'));

Console output is:

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