Skip to content

compose

Composes functions right-to-left: compose(f, g)(x) is equivalent to f(g(x)).

The inverse of pipe, which applies functions left-to-right.

Available since v2.0.0

import { compose } from '@helpers4/function';
compose<A, B>(fn1: function): function
ParameterTypeDescription
fn1function

function — A function that applies fns in reverse order

compose(f, g)(x) is equivalent to f(g(x)). The rightmost function is applied first.

const process = compose(
  String,
  (x: number) => x * 2,
  (x: number) => x + 1
);
process(3); // => "8"

Compose small predicate functions into a single validator.

const validate = compose(
  (ok: boolean) => ok || (() => { throw new Error('invalid'); })(),
  (s: string) => s.length >= 3
);
validate('ab');  // throws
validate('abc'); // => true

View source on GitHub