/
countBy.ts
53 lines (47 loc) · 1.5 KB
/
countBy.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import baseAssignValue from "./.internal/baseAssignValue";
import createAggregator from "./.internal/createAggregator";
import { ArrayIteratee, RecordIteratee } from "./types";
/**
* @ignore
*/
const hasOwnProperty = Object.prototype.hasOwnProperty;
/**
* @ignore
*/
const internalCountBy = createAggregator((result, value, key) => {
if (hasOwnProperty.call(result, key)) {
++result[key];
} else {
baseAssignValue(result, key, 1);
}
});
/**
* Creates an object composed of keys generated from the results of running
* each element of `collection` thru `iteratee`. The corresponding value of
* each key is the number of times the key was returned by `iteratee`. The
* iteratee is invoked with one argument: (value).
*
* @since 5.7.0
* @category Collection
* @param collection The collection to iterate over.
* @param iteratee The iteratee to transform keys.
* @returns Returns the composed aggregate object.
* @example
*
* ```js
* const users = [
* { 'user': 'barney', 'active': true },
* { 'user': 'betty', 'active': true },
* { 'user': 'fred', 'active': false }
* ]
*
* countBy(users, value => value.active);
* // => { 'true': 2, 'false': 1 }
* ```
*/
export function countBy<T>(collection: ArrayLike<T>, iteratee: ArrayIteratee<T>): Record<string, number>;
export function countBy<T>(collection: Record<string, T>, iteratee: RecordIteratee<T>): Record<string, number>;
export function countBy(...args: any[]): any {
return internalCountBy(...args);
}
export default countBy;