| 1 | /**
|
|---|
| 2 | * Count the occurrences of each item in an array
|
|---|
| 3 | * based on a transformation function.
|
|---|
| 4 | *
|
|---|
| 5 | * This function takes an array and a transformation function
|
|---|
| 6 | * that converts each item in the array to a key. It then
|
|---|
| 7 | * counts the occurrences of each transformed item and returns
|
|---|
| 8 | * an object with the transformed items as keys and the counts
|
|---|
| 9 | * as values.
|
|---|
| 10 | *
|
|---|
| 11 | * @template T - The type of the items in the input array.
|
|---|
| 12 | * @template K - The type of keys.
|
|---|
| 13 | * @param {T[]} arr - The input array to count occurrences.
|
|---|
| 14 | * @param {(item: T, index: number, array: readonly T[]) => K} mapper - The transformation function that maps each item, its index, and the array to a key.
|
|---|
| 15 | * @returns {Record<K, number>} An object containing the transformed items as keys and the
|
|---|
| 16 | * counts as values.
|
|---|
| 17 | *
|
|---|
| 18 | * @example
|
|---|
| 19 | * const array = ['a', 'b', 'c', 'a', 'b', 'a'];
|
|---|
| 20 | * const result = countBy(array, x => x);
|
|---|
| 21 | * // result will be { a: 3, b: 2, c: 1 }
|
|---|
| 22 | *
|
|---|
| 23 | * @example
|
|---|
| 24 | * const array = [1, 2, 3, 4, 5];
|
|---|
| 25 | * const result = countBy(array, item => item % 2 === 0 ? 'even' : 'odd');
|
|---|
| 26 | * // result will be { odd: 3, even: 2 }
|
|---|
| 27 | *
|
|---|
| 28 | * @example
|
|---|
| 29 | * // Using index parameter
|
|---|
| 30 | * const array = ['a', 'b', 'c', 'd'];
|
|---|
| 31 | * const result = countBy(array, (item, index) => index < 2 ? 'first' : 'rest');
|
|---|
| 32 | * // result will be { first: 2, rest: 2 }
|
|---|
| 33 | */
|
|---|
| 34 | declare function countBy<T, K extends PropertyKey>(arr: readonly T[], mapper: (item: T, index: number, array: readonly T[]) => K): Record<K, number>;
|
|---|
| 35 |
|
|---|
| 36 | export { countBy };
|
|---|