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
pipereads in the order things happen.composeis the mathematical order, applied right to left.- Both are a one-line reduce over the function list.
Keywords and builtins used here
const
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.
Step 1 of 5 in Composing functions, step 5 of 16 in Functions & patterns.