JS Machine Coding Questions — Implementations You Must Know
Pipe (& Compose)
- pipe(f, g, h)(x) → h(g(f(x))) — left-to-right function composition.
- compose is right-to-left — just use reduceRight.
- Key insight: reduce over the array of functions, passing the accumulated value through each in order.
- Gotcha: pipe with zero functions should be an identity (x => x).
- Gotcha: Each function must accept and return a single value for basic pipe — for async, use async/await inside reduce.
1function pipe(...fns) {
2 return function (value) {
3 return fns.reduce((acc, fn) => fn(acc), value);
4 };
5}
6
7function compose(...fns) {
8 return function (value) {
9 return fns.reduceRight((acc, fn) => fn(acc), value);
10 };
11}
12
13const double = x => x * 2;
14const addTen = x => x + 10;
15const square = x => x * x;
16pipe(double, addTen, square)(3); // 256
17
18// Async pipe
19function asyncPipe(...fns) {
20 return function (value) {
21 return fns.reduce((p, fn) => p.then(fn), Promise.resolve(value));
22 };
23}