aggregateGroups

import { aggregateGroups } from "jsr:@ende/collections";

function

function aggregateGroups<T, A>(record: Readonly<Record<string, ReadonlyArray<T>>>, aggregator: (current: T, key: string, first: boolean, accumulator?: A) => A): Record<string, A>

Applies the given aggregator to each group in the given grouping, returning the results together with the respective group keys

record: Readonly<Record<string, ReadonlyArray<T>>>

The grouping to aggregate.

aggregator: (current: T, key: string, first: boolean, accumulator?: A) => A

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

import { aggregateGroups } from "@ende/collections/aggregate-groups";
import { assertEquals } from "@ende/assert";

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",
});

Source