| 1 | /**
|
|---|
| 2 | * Maps each element of an array based on a provided key-generating function.
|
|---|
| 3 | *
|
|---|
| 4 | * This function takes an array and a function that generates a key from each element. It returns
|
|---|
| 5 | * an object where the keys are the generated keys and the values are the corresponding elements.
|
|---|
| 6 | * If there are multiple elements generating the same key, the last element among them is used
|
|---|
| 7 | * as the value.
|
|---|
| 8 | *
|
|---|
| 9 | * @template T - The type of elements in the array.
|
|---|
| 10 | * @template K - The type of keys.
|
|---|
| 11 | * @param {T[]} arr - The array of elements to be mapped.
|
|---|
| 12 | * @param {(item: T, index: number, array: readonly T[]) => K} getKeyFromItem - A function that generates a key from an element, its index, and the array.
|
|---|
| 13 | * @returns {Record<K, T>} An object where keys are mapped to each element of an array.
|
|---|
| 14 | *
|
|---|
| 15 | * @example
|
|---|
| 16 | * const array = [
|
|---|
| 17 | * { category: 'fruit', name: 'apple' },
|
|---|
| 18 | * { category: 'fruit', name: 'banana' },
|
|---|
| 19 | * { category: 'vegetable', name: 'carrot' }
|
|---|
| 20 | * ];
|
|---|
| 21 | * const result = keyBy(array, item => item.category);
|
|---|
| 22 | * // result will be:
|
|---|
| 23 | * // {
|
|---|
| 24 | * // fruit: { category: 'fruit', name: 'banana' },
|
|---|
| 25 | * // vegetable: { category: 'vegetable', name: 'carrot' }
|
|---|
| 26 | * // }
|
|---|
| 27 | *
|
|---|
| 28 | * @example
|
|---|
| 29 | * // Using index parameter
|
|---|
| 30 | * const items = ['a', 'b', 'c'];
|
|---|
| 31 | * const result = keyBy(items, (item, index) => index);
|
|---|
| 32 | * // result will be: { 0: 'a', 1: 'b', 2: 'c' }
|
|---|
| 33 | */
|
|---|
| 34 | declare function keyBy<T, K extends PropertyKey>(arr: readonly T[], getKeyFromItem: (item: T, index: number, array: readonly T[]) => K): Record<K, T>;
|
|---|
| 35 |
|
|---|
| 36 | export { keyBy };
|
|---|