Function ensureNonEmptyIterable

  • Ensures that a given value is a non-empty iterable.

    - If the value is not iterablereturns `undefined`.
    - If the value is an iterable but contains no entriesreturns `undefined`.
    - If the value is a non-empty iterablereturns a fresh iterable (generator) that yields the first peeked value
    followed by the remaining values. This guarantees restartable iteration even when the original iterable is a
    one-shot generator.

    This function is ideal when you need a safe, non-empty iterable for iteration but cannot consume or trust the original iterable’s internal iterator state.

    Type Parameters

    • T

    Parameters

    • value: Iterable<T, any, any>

      The value to inspect.

    Returns Iterable<T, any, any>

    A restartable iterable containing all values, or undefined if the input was not iterable or contained no items.

    const iter = ensureNonEmptyIterable(['a', 'b']);
    // `iter` is an iterable yielding 'a', 'b'.

    const empty = ensureNonEmptyIterable([]);
    // `undefined`

    const gen = ensureNonEmptyIterable((function*(){ yield 1; yield 2; })());
    // Safe: returns an iterable yielding 1, 2 without consuming the generator.