reduce.js 778 B

123456789101112131415161718192021222324252627282930313233
  1. /**
  2. * Array reduce
  3. */
  4. function reduce(arr, fn, initVal) {
  5. // check for args.length since initVal might be "undefined" see #gh-57
  6. var hasInit = arguments.length > 2,
  7. result = initVal;
  8. if (arr == null || !arr.length) {
  9. if (!hasInit) {
  10. throw new Error('reduce of empty array with no initial value');
  11. } else {
  12. return initVal;
  13. }
  14. }
  15. var i = -1, len = arr.length;
  16. while (++i < len) {
  17. if (!hasInit) {
  18. result = arr[i];
  19. hasInit = true;
  20. } else {
  21. result = fn(result, arr[i], i, arr);
  22. }
  23. }
  24. return result;
  25. }
  26. module.exports = reduce;