Compose and Pipe Functions Left to Right

Build small reusable data pipelines with pipe in left-to-right order and compose in reverse, including argument validation.

JavascriptData Integrity

Code

snippet
export function pipe(...functions) {
  assertFunctions(functions);
  return function piped(value) {
    return functions.reduce((current, fn) => fn(current), value);
  };
}

export function compose(...functions) {
  assertFunctions(functions);
  return pipe(...functions.reverse());
}

function assertFunctions(functions) {
  for (const fn of functions) {
    if (typeof fn !== "function") throw new TypeError("all arguments must be functions");
  }
}

const normalize = pipe(
  (value) => value.trim(),
  (value) => value.toLowerCase(),
  (value) => value.replace(/\s+/g, "-"),
);
console.log(normalize("  Hello   World  "));

const calculate = compose(
  (value) => value * 2,
  (value) => value + 1,
);
console.log(calculate(3));