Implement function composition

Implement compose and pipe with reduceRight and reduce, then make them production-ready: allow the first function to take several arguments, validate inputs, support async steps, and attach context to errors so a failing step is easy to identify.

Basic versions

  • pipe(f, g, h)(x) = h(g(f(x))), using reduce.
  • compose(f, g, h)(x) = f(g(h(x))), using reduceRight.

Production details

  1. First function gets all arguments: pipe(add, double)(2, 3) should call add(2, 3); later functions are unary.
  2. Empty pipeline: return an identity function.
  3. Validation: throw a clear TypeError if a step is not a function, at composition time rather than at call time.
  4. Async support: pipeAsync awaits each step, so steps can return promises.
  5. Error context: wrap failures with the step index and name (using Error's cause).
  6. Preserve this if the composed function will be used as a method (rare, but easy with apply).

Where composition appears

Data transformation pipelines, middleware chains, validation rules, Redux compose for enhancers, and functional libraries (Ramda pipe, Lodash flow).

Complexity

Composition itself is O(k) for k functions; each call runs every step once.

Code example

js
1function pipe(...fns) {
2 fns.forEach((fn, i) => {
3 if (typeof fn !== "function") throw new TypeError(`pipe: argument ${i} is not a function`);
4 });
5 if (fns.length === 0) return (x) => x; // identity
6 const [first, ...rest] = fns;
7 return function (...args) {
8 return rest.reduce((value, fn) => fn.call(this, value), first.apply(this, args));
9 };
10}
11const compose = (...fns) => pipe(...fns.reverse());
12
13function pipeAsync(...fns) {
14 return async (input) => {
15 let value = input;
16 for (const [i, fn] of fns.entries()) {
17 try {
18 value = await fn(value);
19 } catch (err) {
20 throw new Error(`pipeAsync failed at step ${i} (${fn.name || "anonymous"}): ${err.message}`, { cause: err });
21 }
22 }
23 return value;
24 };
25}
26
27const add = (a, b) => a + b;
28const double = (n) => n * 2;
29const toLabel = (n) => `Total: ${n}`;
30
31console.log(pipe(add, double, toLabel)(2, 3)); // Total: 10 (first step receives both args)
32console.log(compose(toLabel, double, add)(2, 3)); // Total: 10
33console.log(pipe()(42)); // 42 (identity)
34
35try {
36 pipe(double, "not a function");
37} catch (e) {
38 console.log(e.message); // pipe: argument 1 is not a function
39}
40
41const fetchUser = async (id) => ({ id, name: "ada lovelace" });
42const capitalise = (u) => ({ ...u, name: u.name.replace(/\b\w/g, (c) => c.toUpperCase()) });
43const requireEmail = function requireEmail(u) {
44 if (!u.email) throw new Error("email missing");
45 return u;
46};
47
48console.log(await pipeAsync(fetchUser, capitalise)(1)); // { id: 1, name: "Ada Lovelace" }
49try {
50 await pipeAsync(fetchUser, capitalise, requireEmail)(1);
51} catch (e) {
52 console.log(e.message); // pipeAsync failed at step 2 (requireEmail): email missing
53}

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app