What is function composition?
Function composition combines small functions into one, where the output of each feeds the input of the next.
compose — applies functions right-to-left.
pipe — applies them left-to-right (reads in execution order).
Building block — each function should do one thing and return a value.
Benefit: build complex behaviour from simple, reusable, testable pieces — a core functional-programming idea.
// Pipe (left-to-right) — more readable
const pipe = (...fns) => (x) => fns.reduce((v, fn) => fn(v), x);
const processUser = pipe(
(name) => name.trim(),
(name) => name.toLowerCase(),
(name) => `user_${name}`,
(name) => ({ username: name, createdAt: Date.now() })
);
console.log(processUser(' John Doe '));
// { username: 'user_john doe', createdAt: 1234567890 }
// Compose (right-to-left)
const compose = (...fns) => (x) => fns.reduceRight((v, fn) => fn(v), x);
const formatPrice = compose(
(s) => `$${s}`, // 3rd: add dollar sign
(n) => n.toFixed(2), // 2nd: format decimals
(n) => n * 1.1 // 1st: add tax
);
console.log(formatPrice(100)); // '$110.00'pipe chains functions left-to-right using reduce: each function's output feeds the next. compose chains right-to-left using reduceRight. processUser trims, lowercases, prefixes, and wraps in an object — each step is a simple, testable function. formatPrice calculates tax, formats decimals, then adds $.
Implement pipe and compose with reduce/reduceRight — common coding question. Pipe is more readable (matches reading order).
Show a practical pipeline (string processing or price formatting). This enables point-free programming where you build complex behavior from simple functions.