array-reduce.js 1.3 KB

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