reduce.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. var arrayReduce = require('./_arrayReduce'),
  2. baseEach = require('./_baseEach'),
  3. baseIteratee = require('./_baseIteratee'),
  4. baseReduce = require('./_baseReduce'),
  5. isArray = require('./isArray');
  6. /**
  7. * Reduces `collection` to a value which is the accumulated result of running
  8. * each element in `collection` thru `iteratee`, where each successive
  9. * invocation is supplied the return value of the previous. If `accumulator`
  10. * is not given, the first element of `collection` is used as the initial
  11. * value. The iteratee is invoked with four arguments:
  12. * (accumulator, value, index|key, collection).
  13. *
  14. * Many lodash methods are guarded to work as iteratees for methods like
  15. * `_.reduce`, `_.reduceRight`, and `_.transform`.
  16. *
  17. * The guarded methods are:
  18. * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`,
  19. * and `sortBy`
  20. *
  21. * @static
  22. * @memberOf _
  23. * @since 0.1.0
  24. * @category Collection
  25. * @param {Array|Object} collection The collection to iterate over.
  26. * @param {Function} [iteratee=_.identity] The function invoked per iteration.
  27. * @param {*} [accumulator] The initial value.
  28. * @returns {*} Returns the accumulated value.
  29. * @see _.reduceRight
  30. * @example
  31. *
  32. * _.reduce([1, 2], function(sum, n) {
  33. * return sum + n;
  34. * }, 0);
  35. * // => 3
  36. *
  37. * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {
  38. * (result[value] || (result[value] = [])).push(key);
  39. * return result;
  40. * }, {});
  41. * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed)
  42. */
  43. function reduce(collection, iteratee, accumulator) {
  44. var func = isArray(collection) ? arrayReduce : baseReduce,
  45. initAccum = arguments.length < 3;
  46. return func(collection, baseIteratee(iteratee, 4), accumulator, initAccum, baseEach);
  47. }
  48. module.exports = reduce;