Typorithm · medium

Implement compose & pipe

compose-pipeinterview-questionscomposepipereduce
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Implement compose & pipe

0%

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.

01

compose uses reduceRight (right-to-left): f(g(x)).

02

pipe uses reduce (left-to-right): g(f(x)).

03

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)) = 12

Read the implementation

Connect each part of the code to the concept before you type.

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);

2. pipe with reduce

reduce walks left-to-right, so pipe(f, g)(x) runs f first then g.

return (x) => fns.reduce((acc, fn) => fn(acc), x);

3. compose order

compose applies right-to-left: g(5) is 10, then f(10) is 11.

compose(f, g)(5); // f(g(5)) = 11

4. pipe order

pipe applies left-to-right: f(5) is 6, then g(6) is 12.

pipe(f, g)(5);    // g(f(5)) = 12

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Implement compose & pipe: Lesson & Practice · Typorithm | ApplyDjinn