Aller au contenu principal

fold()

fold<T, R>(node, handlers): R

Folds over a composite tree, reducing it to a single value. This replaces the recursive operation() method from OOP Composite.


Type Parameters

T: T

The data type in nodes

R: R

The result type


Parameters

node: Composite<T>

The root node to fold

handlers: FoldHandlers<T, R>

Functions to handle leaf and branch nodes


Returns: R

The folded result


Since

2.4.0


Example

// Count all nodes
const count = fold(tree, {
leaf: () => 1,
branch: (_, children) => 1 + children.reduce((a, b) => a + b, 0),
});

// Render to string
const render = fold(tree, {
leaf: (data) => data.name,
branch: (data, children) => `${data.name}(${children.join(", ")})`,
});

FoldHandlers<T, R>

Type

FoldHandlers<T, R> = object

Handlers for folding over a composite tree.


Since

2.4.0


Type Parameters

T: T

The data type in nodes

R: R

The result type


Properties

leaf(): (data) => R

Handle a leaf node. Receives the leaf's data.

data: T
Returns: R

branch(): (data, childResults) => R

Handle a branch node. Receives the branch's data and results from children.

data: T
childResults: R[]
Returns: R

Composite<T>

Type

Composite<T> = Leaf<T> | Branch<T>

A Composite is either a Leaf or a Branch. This discriminated union replaces the OOP Component/Leaf/Composite hierarchy.


Type Parameters

T: T

The data type stored in nodes


Since

2.4.0