Skip to the page

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.

The 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

  1. What is a higher-order function? Name some from your code.
  2. Implement compose and pipe.
  3. Implement Koa-style async middleware and predict the onion order. (TikTok)
  4. Why is Redux middleware curried (store => next => action)?
  5. How do you guard against next() being called twice?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview