Function runningReduce

  • Calls the given reducer on each element of the given collection, passing its result as the accumulator to the next respective call, starting with the given initialValue. Returns all intermediate accumulator results.

    Type Parameters

    • T

      The type of the elements in the array.

    • O

      The type of the accumulator.

    Parameters

    • array: readonly T[]

      The array to reduce.

    • reducer: ((accumulator: O, current: T, currentIndex: number) => O)

      The reducer function to apply to each element.

        • (accumulator, current, currentIndex): O
        • Parameters

          • accumulator: O
          • current: T
          • currentIndex: number

          Returns O

    • initialValue: O

      The initial value of the accumulator.

    Returns O[]

    An array of all intermediate accumulator results.

    import { runningReduce } from "@std/collections/running-reduce";
    import { assertEquals } from "@std/assert";

    const numbers = [1, 2, 3, 4, 5];
    const sumSteps = runningReduce(numbers, (sum, current) => sum + current, 0);

    assertEquals(sumSteps, [1, 3, 6, 10, 15]);