array-reduce.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. var global = require('../internals/global');
  2. var aCallable = require('../internals/a-callable');
  3. var toObject = require('../internals/to-object');
  4. var IndexedObject = require('../internals/indexed-object');
  5. var lengthOfArrayLike = require('../internals/length-of-array-like');
  6. var TypeError = global.TypeError;
  7. // `Array.prototype.{ reduce, reduceRight }` methods implementation
  8. var createMethod = function (IS_RIGHT) {
  9. return function (that, callbackfn, argumentsLength, memo) {
  10. aCallable(callbackfn);
  11. var O = toObject(that);
  12. var self = IndexedObject(O);
  13. var length = lengthOfArrayLike(O);
  14. var index = IS_RIGHT ? length - 1 : 0;
  15. var i = IS_RIGHT ? -1 : 1;
  16. if (argumentsLength < 2) while (true) {
  17. if (index in self) {
  18. memo = self[index];
  19. index += i;
  20. break;
  21. }
  22. index += i;
  23. if (IS_RIGHT ? index < 0 : length <= index) {
  24. throw TypeError('Reduce of empty array with no initial value');
  25. }
  26. }
  27. for (;IS_RIGHT ? index >= 0 : length > index; index += i) if (index in self) {
  28. memo = callbackfn(memo, self[index], index, O);
  29. }
  30. return memo;
  31. };
  32. };
  33. module.exports = {
  34. // `Array.prototype.reduce` method
  35. // https://tc39.es/ecma262/#sec-array.prototype.reduce
  36. left: createMethod(false),
  37. // `Array.prototype.reduceRight` method
  38. // https://tc39.es/ecma262/#sec-array.prototype.reduceright
  39. right: createMethod(true)
  40. };