UNPKG

typedash

Version:

modern, type-safe collection of utility functions

1 lines 1.55 kB
{"version":3,"sources":["../../src/functions/groupBy/groupBy.ts"],"names":[],"mappings":";AA4BO,SAAS,QACd,OACA,QACyB;AACzB,UAAQ,SAAS,CAAC,GAAG;AAAA,IACnB,CAAC,aAAa,gBAAgB;AAC5B,YAAM,MAAM,OAAO,WAAW;AAG9B,kBAAY,GAAG,MAAM,CAAC;AAEtB,kBAAY,GAAG,EAAG,KAAK,WAAW;AAElC,aAAO;AAAA,IACT;AAAA,IACA,CAAC;AAAA,EACH;AACF","sourcesContent":["import { Maybe } from '../../types';\n\n/**\n * Takes an array and returns an object with the keys of the array mapped to the items of the array.\n * @param array The array to iterate over.\n * @param getter The function used to extract the key from each element.\n * @returns An object with the keys mapped to the elements.\n * @example\n * ```ts\n * groupBy(\n * [\n * { id: 'a', value: 1 },\n * { id: 'b', value: 1 },\n * { id: 'c', value: 2 },\n * ],\n * (item) => item.value\n * )\n * // {\n * // 1: [\n * // { id: 'a', value: 1 },\n * // { id: 'b', value: 1 },\n * // ],\n * // 2: [\n * // { id: 'c', value: 2 },\n * // ],\n * // }\n * ```\n */\nexport function groupBy<T, K extends string>(\n array: Maybe<readonly T[]>,\n getter: (item: T) => K\n): Partial<Record<K, T[]>> {\n return (array ?? []).reduce(\n (draftGroups, currentItem) => {\n const key = getter(currentItem);\n\n // eslint-disable-next-line no-param-reassign\n draftGroups[key] ??= [];\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n draftGroups[key]!.push(currentItem);\n\n return draftGroups;\n },\n {} as Partial<Record<K, T[]>>\n );\n}\n"]}