sum.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. var arraySum = require('../internal/arraySum'),
  2. baseCallback = require('../internal/baseCallback'),
  3. baseSum = require('../internal/baseSum'),
  4. isArray = require('../lang/isArray'),
  5. isIterateeCall = require('../internal/isIterateeCall'),
  6. toIterable = require('../internal/toIterable');
  7. /**
  8. * Gets the sum of the values in `collection`.
  9. *
  10. * @static
  11. * @memberOf _
  12. * @category Math
  13. * @param {Array|Object|string} collection The collection to iterate over.
  14. * @param {Function|Object|string} [iteratee] The function invoked per iteration.
  15. * @param {*} [thisArg] The `this` binding of `iteratee`.
  16. * @returns {number} Returns the sum.
  17. * @example
  18. *
  19. * _.sum([4, 6]);
  20. * // => 10
  21. *
  22. * _.sum({ 'a': 4, 'b': 6 });
  23. * // => 10
  24. *
  25. * var objects = [
  26. * { 'n': 4 },
  27. * { 'n': 6 }
  28. * ];
  29. *
  30. * _.sum(objects, function(object) {
  31. * return object.n;
  32. * });
  33. * // => 10
  34. *
  35. * // using the `_.property` callback shorthand
  36. * _.sum(objects, 'n');
  37. * // => 10
  38. */
  39. function sum(collection, iteratee, thisArg) {
  40. if (thisArg && isIterateeCall(collection, iteratee, thisArg)) {
  41. iteratee = undefined;
  42. }
  43. iteratee = baseCallback(iteratee, thisArg, 3);
  44. return iteratee.length == 1
  45. ? arraySum(isArray(collection) ? collection : toIterable(collection), iteratee)
  46. : baseSum(collection, iteratee);
  47. }
  48. module.exports = sum;