Skip to content
GreenSnippets

Compose and pipe functions

Chain single-argument functions left-to-right with pipe, or right-to-left with compose.

JavaScript
const pipe = (...fns) => (input) => fns.reduce((value, fn) => fn(value), input);
const compose = (...fns) => (input) => fns.reduceRight((value, fn) => fn(value), input);

Example / expected output

Output
const clean = pipe((s) => s.trim(), (s) => s.toLowerCase());
clean("  HeLLo ") // "hello"

How it works

pipe(a, b, c)(x) reads in execution order: c(b(a(x))). compose is the same chain reversed, matching mathematical notation. Each function receives the previous return value.

  • JavaScript Tested

    Run a function only once

    Wrap a function so it executes on the first call and returns the same result afterwards.

  • JavaScript Tested

    Memoize a function

    Cache results by argument so expensive pure functions only run once per distinct input.

  • JavaScript Tested

    Curry a function

    Turn a multi-argument function into one that can be called a few arguments at a time.