JavaScriptMedium
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))), usingreduce.compose(f, g, h)(x)=f(g(h(x))), usingreduceRight.
Production details
- First function gets all arguments:
pipe(add, double)(2, 3)should calladd(2, 3); later functions are unary. - Empty pipeline: return an identity function.
- Validation: throw a clear
TypeErrorif a step is not a function, at composition time rather than at call time. - Async support:
pipeAsyncawaits each step, so steps can return promises. - Error context: wrap failures with the step index and name (using
Error'scause). - Preserve
thisif the composed function will be used as a method (rare, but easy withapply).
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; // identity6 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());1213function 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}2627const add = (a, b) => a + b;28const double = (n) => n * 2;29const toLabel = (n) => `Total: ${n}`;3031console.log(pipe(add, double, toLabel)(2, 3)); // Total: 10 (first step receives both args)32console.log(compose(toLabel, double, add)(2, 3)); // Total: 1033console.log(pipe()(42)); // 42 (identity)3435try {36 pipe(double, "not a function");37} catch (e) {38 console.log(e.message); // pipe: argument 1 is not a function39}4041const 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};4748console.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 missing53}
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.