array-reduce.js 1.3 KB

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