reduceRight.js 926 B

12345678910111213141516171819202122232425262728293031323334
  1. /**
  2. * Array reduceRight
  3. */
  4. function reduceRight(arr, fn, initVal) {
  5. // check for args.length since initVal might be "undefined" see #gh-57
  6. var hasInit = arguments.length > 2;
  7. if (arr == null || !arr.length) {
  8. if (hasInit) {
  9. return initVal;
  10. } else {
  11. throw new Error('reduce of empty array with no initial value');
  12. }
  13. }
  14. var i = arr.length, result = initVal, value;
  15. while (--i >= 0) {
  16. // we iterate over sparse items since there is no way to make it
  17. // work properly on IE 7-8. see #64
  18. value = arr[i];
  19. if (!hasInit) {
  20. result = value;
  21. hasInit = true;
  22. } else {
  23. result = fn(result, value, i, arr);
  24. }
  25. }
  26. return result;
  27. }
  28. module.exports = reduceRight;