CyrefJS
CCyrefJS
فا
Back to documentation
Function/Since 1.38.0

compose

Combines multiple functions into a single function that executes them from right to left.

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

Parameters

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

The functions to compose. Each function receives the result of the next function in the sequence.

Returns

(value: T) => T

A new function that applies the provided functions from right to left.

Examples

01

Basic usage

Compose multiple functions and execute them from right to left.

TypeScript
import { compose } from "@cyref/js";

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

const transform = compose(double, addTen);

const result = transform(5);

console.log(result);
// 30
02

Multiple functions

Multiple functions can be composed into a single transformation pipeline.

TypeScript
import { compose } from "@cyref/js";

const double = (value: number) => value * 2;
const addFive = (value: number) => value + 5;
const square = (value: number) => value * value;

const transform = compose(double, addFive, square);

const result = transform(3);

console.log(result);
// 23
03

Execution order

Functions are executed from right to left. The rightmost function receives the original value first.

TypeScript
import { compose } from "@cyref/js";

const addTwo = (value: number) => value + 2;
const multiplyByThree = (value: number) => value * 3;

const transform = compose(addTwo, multiplyByThree);

const result = transform(4);

// multiplyByThree(4) -> 12
// addTwo(12) -> 14

console.log(result);
// 14
04

String transformations

compose can be used to build reusable string transformation pipelines.

TypeScript
import { compose } from "@cyref/js";

const trim = (value: string) => value.trim();
const toUpperCase = (value: string) => value.toUpperCase();
const addPrefix = (value: string) => `Result: ${value}`;

const transform = compose(
  addPrefix,
  toUpperCase,
  trim,
);

const result = transform("  hello world  ");

console.log(result);
// "Result: HELLO WORLD"
05

Single function

compose can also be used with a single function.

TypeScript
import { compose } from "@cyref/js";

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

const transform = compose(double);

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