createAggregator.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435
  1. var baseCallback = require('./baseCallback'),
  2. baseEach = require('./baseEach'),
  3. isArray = require('../lang/isArray');
  4. /**
  5. * Creates a `_.countBy`, `_.groupBy`, `_.indexBy`, or `_.partition` function.
  6. *
  7. * @private
  8. * @param {Function} setter The function to set keys and values of the accumulator object.
  9. * @param {Function} [initializer] The function to initialize the accumulator object.
  10. * @returns {Function} Returns the new aggregator function.
  11. */
  12. function createAggregator(setter, initializer) {
  13. return function(collection, iteratee, thisArg) {
  14. var result = initializer ? initializer() : {};
  15. iteratee = baseCallback(iteratee, thisArg, 3);
  16. if (isArray(collection)) {
  17. var index = -1,
  18. length = collection.length;
  19. while (++index < length) {
  20. var value = collection[index];
  21. setter(result, value, iteratee(value, index, collection), collection);
  22. }
  23. } else {
  24. baseEach(collection, function(value, key, collection) {
  25. setter(result, value, iteratee(value, key, collection), collection);
  26. });
  27. }
  28. return result;
  29. };
  30. }
  31. module.exports = createAggregator;