Packages@accelint/coreComposition
compose
Combine two or more functions to create a new function that passes results from one function to the next, executing right-to-left.
Usage
import { compose } from '@accelint/core/composition/compose';
// Basic usage - read from right to left
const transform = compose(
(x: number) => x.toString(),
(x: number) => x + 3,
(x: number) => x * 2
);
transform(5); // "13"Reference
function compose<Fns extends CompositionArray>(
...fns: Fns
): (...args: ComposeParams<Fns>) => ComposeReturn<Fns>Parameters
| Parameter | Type | Description |
|---|---|---|
...fns | Function array | The functions to compose. All functions except the last must be unary. The last function can be n-ary. |
Returns
Returns a function that executes the composed functions right-to-left, passing each result to the next function.
Type Parameters
Fns- Array of functions where all except the last must be unaryComposeParams<Fns>- Inferred parameter types of the last functionComposeReturn<Fns>- Inferred return type of the first function
Examples
Example: Mathematical composition
import { compose } from '@accelint/core/composition/compose';
// Traditional math notation: f(g(x))
const double = (x: number) => x * 2;
const addTen = (x: number) => x + 10;
const square = (x: number) => x * x;
const f = compose(square, addTen, double);
f(5); // 400 (square(addTen(double(5))) = (10 + 10)² = 400)Example: Data processing pipeline
import { compose } from '@accelint/core/composition/compose';
const uppercase = (s: string) => s.toUpperCase();
const addExclamation = (s: string) => `${s}!`;
const trim = (s: string) => s.trim();
const shout = compose(uppercase, addExclamation, trim);
shout(' hello '); // "HELLO!"Good to know:
composeexecutes right-to-left (mathematical composition order), whilepipeexecutes left-to-right (reading order). They solve the same problem with different execution orders. Choosepipefor more readable data transformation pipelines, orcomposewhen following mathematical notation.