Skip to content

Function: recurse()

recurse<T>(condition, project, options): Operator<T, T>

Defined in: operators/recurse.ts:40

Creates a stream operator that recursively processes values from a source stream.

This operator is designed for traversing tree-like or hierarchical data structures. For each value from the source, it checks if it meets a condition. If it does, it applies a project function to get a new "inner" stream of children. These children are then added to an internal queue and processed in the same recursive manner.

The operator supports both depth-first and breadth-first traversal strategies and can be configured with a maximum recursion depth to prevent runaway processing.

Type Parameters

T

T = any

The type of the values in the source and output streams.

Parameters

condition

(value) => CallbackReturnType<boolean>

A function that returns a boolean indicating whether to recurse on a value.

project

(value) => Stream<T> | CallbackReturnType<T> | T[]

A function that takes a value and returns a stream of new values to be recursively processed.

options

RecurseOptions = {}

An optional configuration object for traversal behavior.

Returns

Operator<T, T>

An Operator instance that can be used in a stream's pipe method.

Examples

From recurse.spec.ts:4

typescript
const condition = (value: number) => value <= 3;
const project = (value: number) => {
  return from(value < 3 ? [value + 1] : []);
};
const stream: Stream<number> = from([1]);
const result: number[] = [];
const outputStream = stream.pipe(recurse(condition, project));
for await (const value of eachValueFrom(outputStream)) {
  result.push(value);
}
expect(result).toEqual([1, 2, 3]);

Released under the MIT License.