Compose and Pipe Functions Left to Right
Build small reusable data pipelines with pipe in left-to-right order and compose in reverse, including argument validation.
Code
export function pipe(...functions) {
assertFunctions(functions);
return function piped(value) {
return functions.reduce((current, fn) => fn(current), value);
};
}
export function compose(...functions) {
assertFunctions(functions);
return pipe(...functions.reverse());
}
function assertFunctions(functions) {
for (const fn of functions) {
if (typeof fn !== "function") throw new TypeError("all arguments must be functions");
}
}
const normalize = pipe(
(value) => value.trim(),
(value) => value.toLowerCase(),
(value) => value.replace(/\s+/g, "-"),
);
console.log(normalize(" Hello World "));
const calculate = compose(
(value) => value * 2,
(value) => value + 1,
);
console.log(calculate(3));Output
Captured from a sandboxed run of this snippet in the build pipeline.
hello-world
8Inside the snippet
Compose and Pipe Functions Left to Right is built around the functions pipe, piped, compose and assertFunctions.
Repetition is confined to for (const fn of functions) — the rest of the file is straight-line. A guard precedes the TypeError: bad state stops the flow there instead of continuing.
The input functions is mutated in place — callers that need the original must pass a copy.
Points of care
- The guard
typeof fn !== "function"short-circuits the flow with an earlythrowwhen its condition holds. functionsis mutated in place — the value you pass will not be the same afterward.
Using it
The main signature reads export function pipe(...functions)
The surface worth importing is pipe; the helpers around it are private to the snippet.
Key statements
return functions.reduce((current, fn) => fn(current), value);
if (typeof fn !== "function") throw new TypeError("all arguments must be functions");
return pipe(...functions.reverse());
Interactive Tools for This Topic
FAQ
- Does `pipe` modify its input?
- Yes — `functions` is mutated in place. Pass a copy if the caller needs the original preserved.
- Is there a failure path for bad input?
- It throws `TypeError` before any real work runs, via the guard `typeof fn !== "function"` — handle it at the call site or let it propagate deliberately.
- Can I paste this into a project as-is?
- Yes. Paste it in and run; no package manager step is needed. The file defines `pipe`, `piped`, `compose` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.