CyrefJS
CCyrefJS
فا
Back to documentation
Function/Since 1.38.0

pipe

Creates a function that passes a value through a sequence of functions from left to right.

pipe(functions):(value: T) => T

Parameters

functionsArray<(value: T) => T>optional

Functions to execute sequentially from left to right. Each function receives the result of the previous function.

Returns

(value: T) => T

Returns a function that passes its input through all provided functions in order.

Examples

01

Basic usage

Functions are executed from left to right.

TypeScript
const addTen = (value: number) => value + 10;
const double = (value: number) => value * 2;

const transform = pipe(addTen, double);

console.log(transform(5));
// 30
02

Execution order

The result of each function becomes the input of the next function.

TypeScript
const addTen = (value: number) => value + 10;
const multiplyByTwo = (value: number) => value * 2;
const subtractFive = (value: number) => value - 5;

const transform = pipe(
  addTen,
  multiplyByTwo,
  subtractFive,
);

console.log(transform(5));
// 25

// 5 -> 15 -> 30 -> 25
03

String transformations

pipe can be used to chain multiple string transformations.

TypeScript
const trim = (value: string) => value.trim();
const toLowerCase = (value: string) => value.toLowerCase();
const addPrefix = (value: string) => `user:${value}`;

const normalize = pipe(
  trim,
  toLowerCase,
  addPrefix,
);

console.log(normalize("  AMIR  "));
// user:amir
04

Multiple functions

Any number of compatible functions can be passed to pipe.

TypeScript
const increment = (value: number) => value + 1;
const double = (value: number) => value * 2;
const square = (value: number) => value * value;

const transform = pipe(
  increment,
  double,
  square,
);

console.log(transform(2));
// 36
05

Without functions

When no functions are provided, the returned function returns the original value unchanged.

TypeScript
const identity = pipe<number>();

console.log(identity(42));
// 42
06

Single function

A single function can also be passed and is applied directly to the input.

TypeScript
const double = (value: number) => value * 2;

const transform = pipe(double);

console.log(transform(5));
// 10
Built with@cyref/js·Official documentation