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-06 10:26:26 +00:00
|
|
|
import { mapValues } from "./map_values.ts";
|
|
|
|
|
|
|
|
/**
|
2023-09-21 10:18:57 +00:00
|
|
|
* Applies the given reducer to each group in the given grouping, returning the
|
2022-11-25 11:40:23 +00:00
|
|
|
* results together with the respective group keys.
|
2021-09-06 10:26:26 +00:00
|
|
|
*
|
2024-05-20 07:34:47 +00:00
|
|
|
* @typeParam T input type of an item in a group in the given grouping.
|
|
|
|
* @typeParam A type of the accumulator value, which will match the returned
|
2024-05-06 07:51:20 +00:00
|
|
|
* record's values.
|
|
|
|
*
|
|
|
|
* @param record The grouping to reduce.
|
|
|
|
* @param reducer The reducer function to apply to each group.
|
|
|
|
* @param initialValue The initial value of the accumulator.
|
|
|
|
*
|
2024-05-08 06:18:26 +00:00
|
|
|
* @returns A record with the same keys as the input grouping, where each value
|
|
|
|
* is the result of applying the reducer to the respective group.
|
|
|
|
*
|
2024-05-06 07:51:20 +00:00
|
|
|
* @example Basic usage
|
2021-09-06 10:26:26 +00:00
|
|
|
* ```ts
|
2024-04-29 02:57:30 +00:00
|
|
|
* import { reduceGroups } from "@std/collections/reduce-groups";
|
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-06 10:26:26 +00:00
|
|
|
*
|
|
|
|
* const votes = {
|
2024-05-06 07:51:20 +00:00
|
|
|
* Woody: [2, 3, 1, 4],
|
|
|
|
* Buzz: [5, 9],
|
2022-11-25 11:40:23 +00:00
|
|
|
* };
|
|
|
|
*
|
2024-05-06 07:51:20 +00:00
|
|
|
* const totalVotes = reduceGroups(votes, (sum, vote) => sum + vote, 0);
|
2021-09-06 10:26:26 +00:00
|
|
|
*
|
|
|
|
* assertEquals(totalVotes, {
|
2024-05-06 07:51:20 +00:00
|
|
|
* Woody: 10,
|
|
|
|
* Buzz: 14,
|
2022-11-25 11:40:23 +00:00
|
|
|
* });
|
2021-09-06 10:26:26 +00:00
|
|
|
* ```
|
|
|
|
*/
|
|
|
|
export function reduceGroups<T, A>(
|
2023-09-21 10:18:57 +00:00
|
|
|
record: Readonly<Record<string, ReadonlyArray<T>>>,
|
2021-09-06 10:26:26 +00:00
|
|
|
reducer: (accumulator: A, current: T) => A,
|
|
|
|
initialValue: A,
|
|
|
|
): Record<string, A> {
|
2024-05-07 07:11:55 +00:00
|
|
|
return mapValues(record, (value) => value.reduce(reducer, initialValue));
|
2021-09-06 10:26:26 +00:00
|
|
|
}
|