Compose Middleware Style Functions

Compose a list of functions so each wraps the next, matching the middleware style used by many web frameworks.

JavascriptResilience

Code

javascriptsnippet
10 lines
export function compose(...middleware) {
  if (middleware.length === 0) return (input) => input;
  return middleware.reduceRight((next, layer) => {
    return (input) => layer(input, next);
  });
}

export function pipe(...transforms) {
  return (input) => transforms.reduce((value, fn) => fn(value), input);
}

How it works

Compose Middleware Style Functions keeps everything in the functions compose and pipe.

Caveats

  • The guard middleware.length === 0 short-circuits the flow with an early return when its condition holds.

Using it

Entry signature: export function compose(...middleware)

The surface worth importing is compose; the helpers around it are private to the snippet.

Key statements

return (input) => transforms.reduce((value, fn) => fn(value), input);
if (middleware.length === 0) return (input) => input;
return middleware.reduceRight((next, layer) => {
return (input) => layer(input, next);
});

Interactive Tools for This Topic

FAQ

Can I paste this into a project as-is?
Yes. Paste it in and run; no package manager step is needed. The file defines `compose`, `pipe` at load time.