countBy.js 1.9 KB

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