Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
80742 views
1
var createAggregator = require('../internal/createAggregator');
2
3
/** Used for native method references. */
4
var objectProto = Object.prototype;
5
6
/** Used to check objects for own properties. */
7
var hasOwnProperty = objectProto.hasOwnProperty;
8
9
/**
10
* Creates an object composed of keys generated from the results of running
11
* each element of `collection` through `iteratee`. The corresponding value
12
* of each key is the number of times the key was returned by `iteratee`.
13
* The `iteratee` is bound to `thisArg` and invoked with three arguments:
14
* (value, index|key, collection).
15
*
16
* If a property name is provided for `iteratee` the created `_.property`
17
* style callback returns the property value of the given element.
18
*
19
* If a value is also provided for `thisArg` the created `_.matchesProperty`
20
* style callback returns `true` for elements that have a matching property
21
* value, else `false`.
22
*
23
* If an object is provided for `iteratee` the created `_.matches` style
24
* callback returns `true` for elements that have the properties of the given
25
* object, else `false`.
26
*
27
* @static
28
* @memberOf _
29
* @category Collection
30
* @param {Array|Object|string} collection The collection to iterate over.
31
* @param {Function|Object|string} [iteratee=_.identity] The function invoked
32
* per iteration.
33
* @param {*} [thisArg] The `this` binding of `iteratee`.
34
* @returns {Object} Returns the composed aggregate object.
35
* @example
36
*
37
* _.countBy([4.3, 6.1, 6.4], function(n) {
38
* return Math.floor(n);
39
* });
40
* // => { '4': 1, '6': 2 }
41
*
42
* _.countBy([4.3, 6.1, 6.4], function(n) {
43
* return this.floor(n);
44
* }, Math);
45
* // => { '4': 1, '6': 2 }
46
*
47
* _.countBy(['one', 'two', 'three'], 'length');
48
* // => { '3': 2, '5': 1 }
49
*/
50
var countBy = createAggregator(function(result, value, key) {
51
hasOwnProperty.call(result, key) ? ++result[key] : (result[key] = 1);
52
});
53
54
module.exports = countBy;
55
56