esnext.iterator.reduce.js 1009 B

123456789101112131415161718192021222324252627282930
  1. 'use strict';
  2. var $ = require('../internals/export');
  3. var iterate = require('../internals/iterate');
  4. var aCallable = require('../internals/a-callable');
  5. var getIteratorDirect = require('../internals/get-iterator-direct');
  6. var $TypeError = TypeError;
  7. // `Iterator.prototype.reduce` method
  8. // https://github.com/tc39/proposal-iterator-helpers
  9. $({ target: 'Iterator', proto: true, real: true }, {
  10. reduce: function reduce(reducer /* , initialValue */) {
  11. var record = getIteratorDirect(this);
  12. aCallable(reducer);
  13. var noInitial = arguments.length < 2;
  14. var accumulator = noInitial ? undefined : arguments[1];
  15. var counter = 0;
  16. iterate(record, function (value) {
  17. if (noInitial) {
  18. noInitial = false;
  19. accumulator = value;
  20. } else {
  21. accumulator = reducer(accumulator, value, counter);
  22. }
  23. counter++;
  24. }, { IS_RECORD: true });
  25. if (noInitial) throw $TypeError('Reduce of empty iterator with no initial value');
  26. return accumulator;
  27. }
  28. });