Function reduceIterator

  • Given an Iterable or IterableIterator, a reducer, and an initial value, return a new IterableIterator that yields values that are automatically piped through said reducer.

    Type Parameters

    • TValue

      The value returned from the iterator

    • TReducerReturn

      The return type of your reducer function

    • TReturn = undefined | TValue

      If your iterator has a return type it must be the same as TIteratorValue, otherwise undefined

    • TNext = any

      The type your iterator is expecting as what's passed to its next function. For generators this is the type returned after a yield.

    Parameters

    • iterator: IteratorArg<TValue, TReturn, TNext>

      The iterator you wish to reduce over

    • reducer: ((carry, arg) => TReducerReturn)

      A function to use to reduce the elements iterator produces

        • (carry, arg): TReducerReturn
        • Parameters

          • carry: TReducerReturn
          • arg: TValue

          Returns TReducerReturn

    • initial: TReducerReturn

      The initial value to pass to reducer with the first element

    Returns AugmentedIterator<TReducerReturn, TReturn, TNext>

    Example

    const set: Set<number> = new Set([1, 2, 3, 4, 5]);

    const summingIterator = reduceIterator(
    set.values(),
    (carry: number, item: number): number => {
    return carry + item;
    },
    0,
    );
    // summingIterator will now yield the sum for each value seen thus far

    const finalValues = Array.from(summingIterator);
    // finalValues will now be [1,3,6,10,15];

Generated using TypeDoc