compose
Composes functions from right to left.
1/**
2 * Composes functions from right to left.
3 *
4 * @param funcs - A list of functions to compose.
5 * @returns A function applying them from right to left.
6 *
7 * @example
8 * const double = (x: number) => x * 2;
9 * const square = (x: number) => x * x;
10 * const result = compose(square, double)(3); // square(double(3)) = 36
11 */
12export function compose<T>(
13 ...funcs: Array<(arg: any) => any>
14): (input: T) => any {
15 return (input: T) =>
16 funcs.reduceRight((acc, fn) => fn(acc), input);
17}
Right-to-Left Function Composition
Mirrors traditional mathematical notation (
f(g(x))
), making it ideal for functional programming patterns.Concise Data Flow Representation
Enables expressing transformations compactly, reducing boilerplate in layered operations.
Minimal and Efficient
Uses
reduceRight
for optimized execution with no external dependencies.Flexible and Reusable
Works with any number of unary functions, allowing dynamic or declarative pipeline construction.
Tests | Examples
1test('compose - applies functions from right to left', () => {
2 const double = (x: number) => x * 2;
3 const square = (x: number) => x * x;
4 const result = compose(square, double)(3); // square(double(3)) = 36
5 expect(result).toBe(36);
6});
7
8test('compose - works with one function', () => {
9 const toUpper = (s: string) => s.toUpperCase();
10 const fn = compose(toUpper);
11 expect(fn('hello')).toBe('HELLO');
12});
13
14test('compose - works with no functions', () => {
15 const fn = compose();
16 expect(fn('data')).toBe('data');
17});
18
19test('compose - works with multiple transformations', () => {
20 const trim = (s: string) => s.trim();
21 const exclaim = (s: string) => s + '!';
22 const toUpper = (s: string) => s.toUpperCase();
23
24 const fn = compose(exclaim, toUpper, trim);
25 expect(fn(' hello ')).toBe('HELLO!');
26});
Common Use Cases
Mathematical and Algorithmic Chains
Build sequences like
normalize → scale → clamp
in signal processing or math libraries.Functional Data Transformation
Compose string manipulation, formatting, and filtering into reusable pipelines.
Middleware or Enhancer Composition
Combine higher-order functions (e.g., in Redux, Express, or custom middlewares) into a single callable.
Selector or Accessor Pipelines
Chain accessor logic when working with complex or nested state structures.
Declarative Business Logic
Compose small business rule functions into higher-level workflows for clarity and reusability.