countBy.js
 1  var baseAssignValue = require('./_baseAssignValue'),
 2      createAggregator = require('./_createAggregator');
 3  
 4  /** Used for built-in method references. */
 5  var objectProto = Object.prototype;
 6  
 7  /** Used to check objects for own properties. */
 8  var hasOwnProperty = objectProto.hasOwnProperty;
 9  
10  /**
11   * Creates an object composed of keys generated from the results of running
12   * each element of `collection` thru `iteratee`. The corresponding value of
13   * each key is the number of times the key was returned by `iteratee`. The
14   * iteratee is invoked with one argument: (value).
15   *
16   * @static
17   * @memberOf _
18   * @since 0.5.0
19   * @category Collection
20   * @param {Array|Object} collection The collection to iterate over.
21   * @param {Function} [iteratee=_.identity] The iteratee to transform keys.
22   * @returns {Object} Returns the composed aggregate object.
23   * @example
24   *
25   * _.countBy([6.1, 4.2, 6.3], Math.floor);
26   * // => { '4': 1, '6': 2 }
27   *
28   * // The `_.property` iteratee shorthand.
29   * _.countBy(['one', 'two', 'three'], 'length');
30   * // => { '3': 2, '5': 1 }
31   */
32  var countBy = createAggregator(function(result, value, key) {
33    if (hasOwnProperty.call(result, key)) {
34      ++result[key];
35    } else {
36      baseAssignValue(result, key, 1);
37    }
38  });
39  
40  module.exports = countBy;