Compose functions from left to right
Build one function that passes a value through each function in order.
function pipe(...fns) { return input => fns.reduce((value, fn) => fn(value), input); }
Usage
const lowercase = text => text.toLowerCase();
const capitalize = text => text.charAt(0).toUpperCase() + text.slice(1);
const reverse = text => [...text].reverse().join('');
pipe(lowercase, capitalize, reverse)('HELLO'); // → 'olleH'
pipe()('unchanged'); // → 'unchanged'
Know the limits
- Functions run in the order listed. With no functions, the input comes back unchanged.
- Each step receives one value. For async steps, use a for…of loop with await.
The function above is the code the usage lines run. It does not validate its arguments; add checks where it receives untrusted input.
Source & maintenance
Based on Compose functions from left to right from the original 1loc collection by Nguyen Huu Phuoc. Copyright (c) 2020 phuoc-ng. MIT licensed.
Documented as a reference with executed usage lines. Original MDX retained as inert source evidence.
Maintained by Oveyon. Original source commit: 14b481cf60df. This edition’s file: contents/compose-functions-from-left-to-right.mdx in akamind/1loc, commit 0a77f131b22d. Read the license.
Keep exploring
- Logical xor operator — True when exactly one of two values is truthy.
- Identity function — Return the argument unchanged.
- Box handler — Chain transformations on a value, then unwrap the result.