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

import { mapEntries } from "./map_entries.ts";

/**
 * Applies the given aggregator to each group in the given grouping, returning the
 * results together with the respective group keys
 *
 * @template T Type of the values in the input record.
 * @template A Type of the accumulator value, which will match the returned
 * record's values.
 *
 * @param record The grouping to aggregate.
 * @param aggregator The function to apply to each group.
 *
 * @returns A record with the same keys as the input record, but with the values
 * being the result of applying the aggregator to each group.
 *
 * @example Basic usage
 * ```ts
 * import { aggregateGroups } from "@std/collections/aggregate-groups";
 * import { assertEquals } from "@std/assert/assert-equals";
 *
 * const foodProperties = {
 *   Curry: ["spicy", "vegan"],
 *   Omelette: ["creamy", "vegetarian"],
 * };
 *
 * const descriptions = aggregateGroups(
 *   foodProperties,
 *   (current, key, first, acc) => {
 *     return first
 *       ? `${key} is ${current}`
 *       : `${acc} and ${current}`;
 *   },
 * );
 *
 * assertEquals(descriptions, {
 *   Curry: "Curry is spicy and vegan",
 *   Omelette: "Omelette is creamy and vegetarian",
 * });
 * ```
 */
export function aggregateGroups<T, A>(
  record: Readonly<Record<string, ReadonlyArray<T>>>,
  aggregator: (current: T, key: string, first: boolean, accumulator?: A) => A,
): Record<string, A> {
  return mapEntries(
    record,
    ([key, values]) => [
      key,
      // Need the type assertions here because the reduce type does not support
      // the type transition we need
      values.reduce(
        (accumulator, current, currentIndex) =>
          aggregator(current, key, currentIndex === 0, accumulator),
        undefined as A | undefined,
      ) as A,
    ],
  );
}

// denoCacheMetadata={"headers":{"set-cookie":"__cf_bm=nGwonbcWU0PAZMrznqHvGENMYNlPO0e1WCHbL_i.6jM-1785241874.9482784-1.0.1.1-PDydWikP1yeLVwTUD0jnq2pmmGRJJA3chgik95gdDWgu209qzFhHIpm4R9fGypaS2FM67icTg93Wt8f4RV_jN1XuxetN__RtphJkFUFZfcXbYucAJHT25_aw2zFI9uXO; HttpOnly; SameSite=None; Secure; Path=/; Domain=jsr.io; Expires=Tue, 28 Jul 2026 13:01:15 GMT","vary":"Origin","access-control-expose-headers":"*","x-jsr-backend":"modules","content-type":"text/typescript","alt-svc":"h3=\":443\"; ma=86400","x-robots-tag":"noindex","report-to":"{\"group\":\"cf-nel\",\"max_age\":604800,\"endpoints\":[{\"url\":\"https://a.nel.cloudflare.com/report/v4?s=UW%2FaKGhdpby74sSzySP2otHlnQnhYAE6qjWIdMQr4qgh8IfF9HuBW%2BVuCP43QpUhcrPO9oKt7PmuU80iDBI1JsLgK5wDz%2B3gKmYvpOOmYZjCH2qZAgooD04%3D\"}]}","cross-origin-resource-policy":"cross-origin","nel":"{\"report_to\":\"cf-nel\",\"success_fraction\":0.0,\"max_age\":604800}","server":"cloudflare","cf-ray":"a223e6564eda7db6-LAX","date":"Tue, 28 Jul 2026 12:31:15 GMT","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';","access-control-allow-origin":"*","etag":"\"395f6441c1b5d7773b128b01ad32dc13\"","content-length":"1918","cache-control":"public, max-age=31536000, immutable","x-content-type-options":"nosniff"},"url":"https://jsr.io/@std/collections/0.224.2/aggregate_groups.ts","time":1785241875}