Skip to content

Instantly share code, notes, and snippets.

@r37r0m0d3l
Forked from JamieMason/es6-compose.md
Created June 20, 2020 17:16
Show Gist options
  • Save r37r0m0d3l/afc7a8225409f42fd3cc42b89550f38d to your computer and use it in GitHub Desktop.
Save r37r0m0d3l/afc7a8225409f42fd3cc42b89550f38d to your computer and use it in GitHub Desktop.
ES6 JavaScript compose function

ES6 JavaScript Compose Function

Definition

const compose = (...fns) =>
  fns.reduceRight((prevFn, nextFn) =>
    (...args) => nextFn(prevFn(...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:

example('hello')

Console output is:

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