Yevhen Klymentiev
dark
light
console
darkness
y.klymentiev@gmail.com
Reusable Snippets|Practical utility code for everyday use — custom-built and ready to share

pipe

Composes multiple functions from left to right.

TypeScript
Copied!
1/**
2 * Composes multiple functions from left to right.
3 *
4 * @param funcs - A sequence of functions to apply.
5 * @returns A function that takes an initial value and applies all functions in sequence.
6 *
7 * @example
8 * const double = (x: number) => x * 2;
9 * const square = (x: number) => x * x;
10 * const result = pipe(double, square)(3); // (3 * 2)^2 = 36
11 */
12export function pipe<T>(...funcs: Array<(arg: any) => any>): (input: T) => any {
13  return (input: T) => funcs.reduce((acc, fn) => fn(acc), input);
14}
  • Left-to-Right Function Composition

    Applies functions in intuitive left-to-right order, improving readability over traditional right-to-left compose.

  • Clean and Declarative Syntax

    Encourages a more functional and declarative coding style by chaining pure operations.

  • Flexible Arity and Reusability

    Accepts any number of unary functions, making it suitable for dynamic or configurable pipelines.

  • Minimal Overhead

    Uses a single reduce pass with no external dependencies, ensuring high performance and small footprint.

Tests | Examples

TypeScript
Copied!
1test('pipe - applies functions from left to right', () => {
2  const double = (x: number) => x * 2;
3  const square = (x: number) => x * x;
4  const addOne = (x: number) => x + 1;
5
6  const fn = pipe(double, square, addOne);
7  expect(fn(2)).toBe(17); // ((2 * 2)^2) + 1 = 17
8});
9
10test('pipe - works with a single function', () => {
11  const reverse = (str: string) => str.split('').reverse().join('');
12  const fn = pipe(reverse);
13  expect(fn('abc')).toBe('cba');
14});
15
16test('pipe - works with no functions', () => {
17  const fn = pipe();
18  expect(fn('hello')).toBe('hello');
19});
20
21test('pipe - preserves types through function chain', () => {
22  const toLength = (s: string) => s.length;
23  const double = (n: number) => n * 2;
24  const fn = pipe(toLength, double);
25  expect(fn('test')).toBe(8); // 'test' => 4 => 8
26});

Common Use Cases

  • Data Transformation Pipelines

    Chain formatters, validators, or mappers to transform input step by step (e.g., strings, numbers, objects).

  • Functional UI Logic

    Apply view-model transformations or prop shaping in UI frameworks like React.

  • Form Processing

    Validate, sanitize, and transform form values in a single pass using composed functions.

  • Middleware and Event Handling

    Create layered processing logic (e.g., interceptors, enhancers, event mappers).

  • Math and Signal Processing

    Compose mathematical operations or filters for real-time numeric data processing.

Codebase: Utilities -> Functions -> pipe | Yevhen Klymentiev