typedash
Version:
modern, type-safe collection of utility functions
1 lines • 1.35 kB
Source Map (JSON)
{"version":3,"file":"keyBy-Bx8eEPsQ.cjs","names":[],"sources":["../src/functions/keyBy/keyBy.ts"],"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 draftObject[key] = currentItem;\n\n return draftObject;\n },\n {} as Partial<Record<K, T>>\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAuBA,SAAgB,MACd,OACA,WACuB;AACvB,QAAO,MAAM,QACV,aAAa,gBAAgB;EAC5B,MAAM,MAAM,UAAU,YAAY;AAElC,cAAY,OAAO;AAEnB,SAAO;IAET,EAAE,CACH"}