You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

33 lines
908 B

пре 3 година
  1. var baseIteratee = require('./_baseIteratee'),
  2. baseSum = require('./_baseSum');
  3. /**
  4. * This method is like `_.sum` except that it accepts `iteratee` which is
  5. * invoked for each element in `array` to generate the value to be summed.
  6. * The iteratee is invoked with one argument: (value).
  7. *
  8. * @static
  9. * @memberOf _
  10. * @since 4.0.0
  11. * @category Math
  12. * @param {Array} array The array to iterate over.
  13. * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
  14. * @returns {number} Returns the sum.
  15. * @example
  16. *
  17. * var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }];
  18. *
  19. * _.sumBy(objects, function(o) { return o.n; });
  20. * // => 20
  21. *
  22. * // The `_.property` iteratee shorthand.
  23. * _.sumBy(objects, 'n');
  24. * // => 20
  25. */
  26. function sumBy(array, iteratee) {
  27. return (array && array.length)
  28. ? baseSum(array, baseIteratee(iteratee, 2))
  29. : 0;
  30. }
  31. module.exports = sumBy;