Functional patterns · mid
Higher-order functions, compose, pipe and middleware
A higher-order function takes or returns a function; compose(f, g)(x) is f(g(x)) (right to left), pipe runs left to right, and Koa- or Redux-style middleware is composition where each function decides when to call next, giving the onion order before -> inner -> after.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- Pure functions (same input -> same output, no side effects) are easy to test, memoize and compose.
- compose = (...fns) => (x) => fns.reduceRight((acc, f) => f(acc), x); pipe uses reduce.
- An async pipe reduces over a promise chain.
- Koa-style middleware: dispatch(i) calls fns[i](ctx, () => dispatch(i + 1)). Guard against calling next twice; errors travel through the returned promises.
- Redux middleware has the shape store => next => action; applyMiddleware composes them so each one wraps the next dispatch.
- A tiny Redux store is getState, dispatch (reducer -> new state -> notify listeners) and subscribe (returns unsubscribe).
The red pen
Common traps: mistake → fix
Mistake: compose runs left to right
Fix: compose is right to left; pipe is left to right.
Mistake: Middleware that doesn't await next()
Fix: its 'after' code runs too early.
Easy to hard
Questions interviewers ask, easy to hard
- What is a higher-order function? Name some from your code.
- Implement compose and pipe.
- Implement Koa-style async middleware and predict the onion order. (TikTok)
- Why is Redux middleware curried (store => next => action)?
- How do you guard against next() being called twice?
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.