Skip to content

Function: loop()

loop<T>(initialValue, condition, iterateFn): Stream<T>

Defined in: streams/loop.ts:18

Creates a stream that emits values in a loop based on a condition and an iteration function.

This operator is useful for generating a sequence of values until a specific condition is no longer met. It starts with an initialValue and, for each iteration, it yields the current value and then uses iterateFn to calculate the next value in the sequence.

Type Parameters

T

T = any

The type of the values in the stream.

Parameters

initialValue

T

The starting value for the loop.

condition

(value) => CallbackReturnType<boolean>

A function that returns true to continue the loop and false to stop.

iterateFn

(value) => CallbackReturnType<T>

A function that returns the next value in the sequence.

Returns

Stream<T>

A stream that emits the generated sequence of values.

Examples

From loop.spec.ts:14

typescript
const result = await collect(
  eachValueFrom(
    loop(
      0,
      (x) => x < 5,
      (x) => x + 1
    )
  )
);
expect(result).toEqual([0, 1, 2, 3, 4]);

Released under the MIT License.