typedash
Version:
modern, type-safe collection of utility functions
1 lines • 1.39 kB
Source Map (JSON)
{"version":3,"sources":["../../src/functions/keyBy/keyBy.ts"],"names":[],"mappings":";AAuBO,SAAS,MACd,OACA,WACuB;AACvB,SAAO,MAAM;AAAA,IACX,CAAC,aAAa,gBAAgB;AAC5B,YAAM,MAAM,UAAU,WAAW;AAGjC,kBAAY,GAAG,IAAI;AAEnB,aAAO;AAAA,IACT;AAAA,IACA,CAAC;AAAA,EACH;AACF","sourcesContent":["/**\n * Creates an object composed of keys generated from the results of running each element of `array` through `keyGetter`.\n * The corresponding value of each key is the last element responsible for generating the key.\n * @param array The array to iterate over.\n * @param keyGetter 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 * keyBy(\n * [\n * { id: 'a', value: 1 },\n * { id: 'b', value: 2 },\n * { id: 'c', value: 3 },\n * ],\n * (item) => item.id\n * )\n * // {\n * // a: { id: 'a', value: 1 },\n * // b: { id: 'b', value: 2 },\n * // c: { id: 'c', value: 3 }\n * // }\n * ```\n */\nexport function keyBy<T, K extends PropertyKey>(\n array: readonly T[],\n keyGetter: (item: T) => K\n): Partial<Record<K, T>> {\n return array.reduce(\n (draftObject, currentItem) => {\n const key = keyGetter(currentItem);\n\n // eslint-disable-next-line no-param-reassign\n draftObject[key] = currentItem;\n\n return draftObject;\n },\n {} as Partial<Record<K, T>>\n );\n}\n"]}