2024-01-01 21:11:32 +00:00
|
|
|
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
|
2021-09-18 18:29:29 +00:00
|
|
|
// This module is browser compatible.
|
2021-09-13 05:12:11 +00:00
|
|
|
|
|
|
|
/**
|
2022-11-25 11:40:23 +00:00
|
|
|
* 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.
|
2021-09-13 05:12:11 +00:00
|
|
|
*
|
2024-05-20 07:34:47 +00:00
|
|
|
* @typeParam T The type of the elements in the array.
|
|
|
|
* @typeParam O The type of the accumulator.
|
2024-05-06 07:51:20 +00:00
|
|
|
*
|
|
|
|
* @param array The array to reduce.
|
|
|
|
* @param reducer The reducer function to apply to each element.
|
|
|
|
* @param initialValue The initial value of the accumulator.
|
|
|
|
*
|
2024-05-08 06:18:26 +00:00
|
|
|
* @returns An array of all intermediate accumulator results.
|
|
|
|
*
|
2024-05-06 07:51:20 +00:00
|
|
|
* @example Basic usage
|
2021-09-13 05:12:11 +00:00
|
|
|
* ```ts
|
2024-04-29 02:57:30 +00:00
|
|
|
* import { runningReduce } from "@std/collections/running-reduce";
|
refactor(assert,async,bytes,cli,collections,crypto,csv,data-structures,datetime,dotenv,encoding,expect,fmt,front-matter,fs,html,http,ini,internal,io,json,jsonc,log,media-types,msgpack,net,path,semver,streams,testing,text,toml,ulid,url,uuid,webgpu,yaml): import from `@std/assert` (#5199)
* refactor: import from `@std/assert`
* update
2024-06-30 08:30:10 +00:00
|
|
|
* import { assertEquals } from "@std/assert";
|
2021-09-13 05:12:11 +00:00
|
|
|
*
|
|
|
|
* const numbers = [1, 2, 3, 4, 5];
|
|
|
|
* const sumSteps = runningReduce(numbers, (sum, current) => sum + current, 0);
|
|
|
|
*
|
|
|
|
* assertEquals(sumSteps, [1, 3, 6, 10, 15]);
|
|
|
|
* ```
|
|
|
|
*/
|
|
|
|
export function runningReduce<T, O>(
|
|
|
|
array: readonly T[],
|
2021-10-20 04:35:27 +00:00
|
|
|
reducer: (accumulator: O, current: T, currentIndex: number) => O,
|
2021-09-13 05:12:11 +00:00
|
|
|
initialValue: O,
|
|
|
|
): O[] {
|
|
|
|
let currentResult = initialValue;
|
2021-10-20 04:35:27 +00:00
|
|
|
return array.map((el, currentIndex) =>
|
|
|
|
currentResult = reducer(currentResult, el, currentIndex)
|
|
|
|
);
|
2021-09-13 05:12:11 +00:00
|
|
|
}
|