Function reduce

  • Summarize all values in an iterable using a reducer function.

    Type Parameters

    • T

    Parameters

    • object: Iterable<T>

      The iterable object of interest.

    • fn: ((accumulator, value, index) => T)

      The reducer function to invoke for each value.

        • (accumulator, value, index): T
        • Parameters

          • accumulator: T
          • value: T
          • index: number

          Returns T

    Returns T

    The final accumulated value.

    Notes

    The reduce function follows the conventions of Array#reduce.

    If the iterator is empty, an initial value is required. That value will be used as the return value. If no initial value is provided, an error will be thrown.

    If the iterator contains a single item and no initial value is provided, the single item is used as the return value.

    Otherwise, the reducer is invoked for each element in the iterable. If an initial value is not provided, the first element will be used as the initial accumulated value.

    Complexity

    Linear.

    Example

    import { reduce } from '@lumino/algorithm';

    let data = [1, 2, 3, 4, 5];

    let sum = reduce(data, (a, value) => a + value); // 15
  • Type Parameters

    • T
    • U

    Parameters

    • object: Iterable<T>
    • fn: ((accumulator, value, index) => U)
        • (accumulator, value, index): U
        • Parameters

          • accumulator: U
          • value: T
          • index: number

          Returns U

    • initial: U

    Returns U