flowLoading saved progress…

flow

flow chains functions into a pipeline: it returns a new function that passes its input through each function left to right, feeding every output into the next. It's the readable way to say "trim it, then lowercase it, then slugify it" as data flowing forward — the opposite direction from compose, which runs right to left.

Implement flow(...fns). The returned function passes its arguments to the first function, then that result to the second, and so on, returning the last result. flow() with no functions is the identity.

Signature

function flow(...fns) {
  // returns (x) => fns[n-1](...(fns[1](fns[0](x))))
}

Examples

const inc = (n) => n + 1;
const double = (n) => n * 2;

flow(inc, double)(3); // 8   — (3 + 1) * 2, left to right
flow(double, inc)(3); // 7   — (3 * 2) + 1, order matters
flow(inc, double, (n) => n * n)(2); // 36  — ((2+1)*2)^2
flow()(42);                          // 42  — identity

Notes

  • Left to rightflow(f, g)(x) is g(f(x)): f runs first. This is the reverse of compose.
  • First function, all arguments — only the first function receives the original arguments; each later one gets the previous single return value.
  • Empty flow — returns its first argument unchanged (the identity function).
  • Lazy — building the pipeline calls nothing; the functions run only when the returned function is invoked.
  • Reusable — the returned pipeline can be called many times with different inputs.
Loading editor…