typedash
Version:
modern, type-safe collection of utility functions
1 lines • 1.53 kB
Source Map (JSON)
{"version":3,"file":"groupBy-CTfqrrae.cjs","names":[],"sources":["../src/functions/groupBy/groupBy.ts"],"sourcesContent":["import type { 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 draftGroups[key] ??= [];\n // biome-ignore lint/style/noNonNullAssertion: surely exists because of the line above\n draftGroups[key]!.push(currentItem);\n\n return draftGroups;\n },\n {} as Partial<Record<K, T[]>>\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BA,SAAgB,QACd,OACA,QACyB;AACzB,SAAQ,SAAS,EAAE,EAAE,QAClB,aAAa,gBAAgB;EAC5B,MAAM,MAAM,OAAO,YAAY;AAE/B,cAAY,SAAS,EAAE;AAEvB,cAAY,KAAM,KAAK,YAAY;AAEnC,SAAO;IAET,EAAE,CACH"}