sum.js 721 B

123456789101112131415161718192021222324252627
  1. var helperNumberAdd = require('./helperNumberAdd')
  2. var isFunction = require('./isFunction')
  3. var each = require('./each')
  4. var get = require('./get')
  5. /**
  6. * 求和函数,将数值相加
  7. *
  8. * @param {Array} array 数组
  9. * @param {Function/String} iterate 方法或属性
  10. * @param {Object} context 上下文
  11. * @return {Number}
  12. */
  13. function sum (array, iterate, context) {
  14. var result = 0
  15. each(array, iterate ? isFunction(iterate) ? function () {
  16. result = helperNumberAdd(result, iterate.apply(context, arguments))
  17. } : function (val) {
  18. result = helperNumberAdd(result, get(val, iterate))
  19. } : function (val) {
  20. result = helperNumberAdd(result, val)
  21. })
  22. return result
  23. }
  24. module.exports = sum