typestar

Composition in JavaScript

Small functions, combined left to right or right to left.

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

const trim = (s) => s.trim();
const lower = (s) => s.toLowerCase();
const hyphenate = (s) => s.replaceAll(" ", "-");

const slugify = pipe(trim, lower, hyphenate);
const slugifyBackwards = compose(hyphenate, lower, trim);

console.log(slugify("  Language Basics  "));
console.log(slugifyBackwards("  Async Patterns  "));
console.log(pipe()( "unchanged"));

How it works

  1. pipe reads in the order things happen.
  2. compose is the mathematical order, applied right to left.
  3. Both are a one-line reduce over the function list.

Keywords and builtins used here

The run, in numbers

Lines
14
Characters to type
518
Tokens
158
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 90 seconds.

Type this snippet

Step 1 of 5 in Composing functions, step 5 of 16 in Functions & patterns.

← Previous Next →