reduce.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. var arrayReduce = require('../internal/arrayReduce'),
  2. baseEach = require('../internal/baseEach'),
  3. createReduce = require('../internal/createReduce');
  4. /**
  5. * Reduces `collection` to a value which is the accumulated result of running
  6. * each element in `collection` through `iteratee`, where each successive
  7. * invocation is supplied the return value of the previous. If `accumulator`
  8. * is not provided the first element of `collection` is used as the initial
  9. * value. The `iteratee` is bound to `thisArg` and invoked with four arguments:
  10. * (accumulator, value, index|key, collection).
  11. *
  12. * Many lodash methods are guarded to work as iteratees for methods like
  13. * `_.reduce`, `_.reduceRight`, and `_.transform`.
  14. *
  15. * The guarded methods are:
  16. * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `sortByAll`,
  17. * and `sortByOrder`
  18. *
  19. * @static
  20. * @memberOf _
  21. * @alias foldl, inject
  22. * @category Collection
  23. * @param {Array|Object|string} collection The collection to iterate over.
  24. * @param {Function} [iteratee=_.identity] The function invoked per iteration.
  25. * @param {*} [accumulator] The initial value.
  26. * @param {*} [thisArg] The `this` binding of `iteratee`.
  27. * @returns {*} Returns the accumulated value.
  28. * @example
  29. *
  30. * _.reduce([1, 2], function(total, n) {
  31. * return total + n;
  32. * });
  33. * // => 3
  34. *
  35. * _.reduce({ 'a': 1, 'b': 2 }, function(result, n, key) {
  36. * result[key] = n * 3;
  37. * return result;
  38. * }, {});
  39. * // => { 'a': 3, 'b': 6 } (iteration order is not guaranteed)
  40. */
  41. var reduce = createReduce(arrayReduce, baseEach);
  42. module.exports = reduce;