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>β
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>β
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