1. compose with reduceRight
reduceRight walks the functions right-to-left, so compose(f, g)(x) runs g first then f.
return (x) => fns.reduceRight((acc, fn) => fn(acc), x);Typorithm · medium
Step 1 of 8 · intro card
Implement It
compose(...fns)(x) applies functions right-to-left with reduceRight, so compose(f, g)(x) === f(g(x)). pipe(...fns)(x) applies them left-to-right with reduce, so pipe(f, g)(x) === g(f(x)). The accumulator starts as x and is threaded through each function.
Both compose and pipe take a list of unary functions and return a single function that threads its input through all of them; they differ only in direction.
compose runs right-to-left, matching mathematical notation f ∘ g: it uses reduceRight with the input x as the initial accumulator, so compose(f, g)(x) evaluates f(g(x)).
pipe runs left-to-right, which reads naturally as a data pipeline: it uses reduce with x as the seed, so pipe(f, g)(x) evaluates g(f(x)). The reducer fn(acc) feeds each step's output into the next.
compose uses reduceRight (right-to-left): f(g(x)).
pipe uses reduce (left-to-right): g(f(x)).
The initial accumulator is the input x in both.
function compose(...fns) {
return (x) => fns.reduceRight((acc, fn) => fn(acc), x);
}
function pipe(...fns) {
return (x) => fns.reduce((acc, fn) => fn(acc), x);
}
const f = (n) => n + 1;
const g = (n) => n * 2;
compose(f, g)(5); // f(g(5)) = 11
pipe(f, g)(5); // g(f(5)) = 12Connect each part of the code to the concept before you type.
reduceRight walks the functions right-to-left, so compose(f, g)(x) runs g first then f.
return (x) => fns.reduceRight((acc, fn) => fn(acc), x);reduce walks left-to-right, so pipe(f, g)(x) runs f first then g.
return (x) => fns.reduce((acc, fn) => fn(acc), x);compose applies right-to-left: g(5) is 10, then f(10) is 11.
compose(f, g)(5); // f(g(5)) = 11pipe applies left-to-right: f(5) is 6, then g(6) is 12.
pipe(f, g)(5); // g(f(5)) = 12Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.