// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
// This module is browser compatible.

import { mapValues } from "./map_values.ts";

/**
 * Applies the given reducer to each group in the given grouping, returning the
 * results together with the respective group keys.
 *
 * @template T input type of an item in a group in the given grouping.
 * @template A type of the accumulator value, which will match the returned
 * 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.
 *
 * @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.
 *
 * @example Basic usage
 * ```ts
 * import { reduceGroups } from "@std/collections/reduce-groups";
 * import { assertEquals } from "@std/assert/assert-equals";
 *
 * const votes = {
 *   Woody: [2, 3, 1, 4],
 *   Buzz: [5, 9],
 * };
 *
 * const totalVotes = reduceGroups(votes, (sum, vote) => sum + vote, 0);
 *
 * assertEquals(totalVotes, {
 *   Woody: 10,
 *   Buzz: 14,
 * });
 * ```
 */
export function reduceGroups<T, A>(
  record: Readonly<Record<string, ReadonlyArray<T>>>,
  reducer: (accumulator: A, current: T) => A,
  initialValue: A,
): Record<string, A> {
  return mapValues(record, (value) => value.reduce(reducer, initialValue));
}

// denoCacheMetadata={"headers":{"content-security-policy":"default-src 'none'; script-src 'none'; style-src 'none'; img-src 'none'; font-src 'none'; connect-src 'none'; frame-src 'none'; object-src 'none'; frame-ancestors 'none'; sandbox; form-action 'none';","report-to":"{\"group\":\"cf-nel\",\"max_age\":604800,\"endpoints\":[{\"url\":\"https://a.nel.cloudflare.com/report/v4?s=1TRzLN5HWsXt8KX9cioktYwLHTuj6i052vxVxAutq5uVWCMrrmWBF4WwtBrGpPUYkl4lpaz4Fq3JaotohM6i2cOH654TyDhhgo5brq9VRQaRYU0seWEf%2BAM%3D\"}]}","date":"Tue, 28 Jul 2026 12:31:15 GMT","nel":"{\"report_to\":\"cf-nel\",\"success_fraction\":0.0,\"max_age\":604800}","x-jsr-backend":"modules","cf-ray":"a223e6564f307db6-LAX","x-content-type-options":"nosniff","alt-svc":"h3=\":443\"; ma=86400","set-cookie":"__cf_bm=JfvjmVuL81jgOnsLrO5SLWZzbG57PQcrsSSLmeLeRk0-1785241874.96346-1.0.1.1-eqKSr0HrAnRg3MziQJrCbrDU9Y9uUgZGceuiIA0kUc.8BjG8xf0ZrCT6EolJSEW.Bfzo4c7A.T_Nn7wFgs7eBLWtgxZ1EaEOFw.wyyeIy4_vOOdzDvdBXDa3NiIlSXWt; HttpOnly; SameSite=None; Secure; Path=/; Domain=jsr.io; Expires=Tue, 28 Jul 2026 13:01:15 GMT","vary":"Origin","etag":"\"95e4a737c8b171c840f0730f0a7c0ab7\"","cross-origin-resource-policy":"cross-origin","content-length":"1433","server":"cloudflare","content-type":"text/typescript","cache-control":"public, max-age=31536000, immutable","access-control-allow-origin":"*","access-control-expose-headers":"*","x-robots-tag":"noindex"},"url":"https://jsr.io/@std/collections/0.224.2/reduce_groups.ts","time":1785241875}