Class LazyStream<T>

LazyStream: Handles asynchronous data lazily.

This class enables lazy, on-demand processing of async data sources, such as paginated API responses or infinite streams.

Features:

  • Lazy Evaluation: Data is only processed when requested.
  • Functional API: Supports chaining with map(), filter(), and take().
  • Async Generators: Works with async data sources seamlessly.

Type Parameters

  • T

    The type of elements processed by the stream.

Constructors

Methods

Constructors

  • Creates a new LazyStream instance.

    Type Parameters

    • T

    Parameters

    • generatorFn: (() => AsyncGenerator<T, void, unknown>)

      An async generator function.

        • (): AsyncGenerator<T, void, unknown>
        • Returns AsyncGenerator<T, void, unknown>

    Returns LazyStream<T>

Methods

  • Lazily filters elements based on a predicate function.

    Parameters

    • predicate: ((value: T) => boolean | Promise<boolean>)

      The filtering function.

        • (value): boolean | Promise<boolean>
        • Parameters

          • value: T

          Returns boolean | Promise<boolean>

    Returns LazyStream<T>

    • A new filtered LazyStream.
    const evens = stream.filter(x => x % 2 === 0);
    
  • Lazily applies a transformation function to each element.

    Type Parameters

    • U

      The transformed type.

    Parameters

    • fn: ((value: T) => U | Promise<U>)

      Transformation function.

        • (value): U | Promise<U>
        • Parameters

          • value: T

          Returns U | Promise<U>

    Returns LazyStream<U>

    • A new LazyStream instance.
    const doubled = stream.map(x => x * 2);
    
  • Collects the stream into an array.

    Note: This forces evaluation of all elements (breaking laziness).

    Returns Promise<T[]>

    • A promise resolving to an array of values.
    const values = await stream.toArray();
    
  • Creates a LazyStream from an async generator function.

    Type Parameters

    • T

      The type of elements produced.

    Parameters

    • fn: (() => AsyncGenerator<T, void, unknown>)

      The generator function.

        • (): AsyncGenerator<T, void, unknown>
        • Returns AsyncGenerator<T, void, unknown>

    Returns LazyStream<T>

    • A new LazyStream instance.
    async function* numbers() {
    let i = 1;
    while (true) yield i++;
    }
    const stream = LazyStream.from(numbers);