Snippet

compose() & pipe()

edit

I go over function composition in this blog post, so please read the post for a more detailed explanation.

const compose =
  (...fns) =>
  x =>
    fns.reduceRight((acc, fn) => fn(acc), x)

const pipe =
  (...fns) =>
  x =>
    fns.reduce((acc, fn) => fn(acc), x)

If you want to get real fancy, you can split out and share the reducer.

const apply = (value, fn) => fn(value)

const compose =
  (...fns) =>
  x =>
    fns.reduceRight(apply, x)

const pipe =
  (...fns) =>
  x =>
    fns.reduce(apply, x)

Liked the post?
Give the author a dopamine boost with a few "beard strokes". Click the beard up to 50 times to show your appreciation.

Kyle Shevlin's face, which is mostly a beard with eyes

Kyle Shevlin is the founder & lead software engineer of Agathist, a software development firm with a mission to build good software with good people.

Logo for Data Structures and Algorithms
Data Structures and Algorithms
Check out my courses!
If you enjoy my posts, you might enjoy my courses, too. Click the button to view the course or go to Courses for more information.
Sign up for my newsletter
Let's chat some more about TypeScript, React, and frontend web development. Unsubscribe at any time.