reduce.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. var keys = require('./keys')
  2. /**
  3. * 接收一个函数作为累加器,数组中的每个值(从左到右)开始合并,最终为一个值。
  4. *
  5. * @param {Array} array 数组
  6. * @param {Function} callback 方法
  7. * @param {Object} initialValue 初始值
  8. * @return {Number}
  9. */
  10. function reduce (array, callback, initialValue) {
  11. if (array) {
  12. var len, reduceMethod
  13. var index = 0
  14. var context = null
  15. var previous = initialValue
  16. var isInitialVal = arguments.length > 2
  17. var keyList = keys(array)
  18. if (array.length && array.reduce) {
  19. reduceMethod = function () {
  20. return callback.apply(context, arguments)
  21. }
  22. if (isInitialVal) {
  23. return array.reduce(reduceMethod, previous)
  24. }
  25. return array.reduce(reduceMethod)
  26. }
  27. if (isInitialVal) {
  28. index = 1
  29. previous = array[keyList[0]]
  30. }
  31. for (len = keyList.length; index < len; index++) {
  32. previous = callback.call(context, previous, array[keyList[index]], index, array)
  33. }
  34. return previous
  35. }
  36. }
  37. module.exports = reduce