es.iterator.reduce.js 1.1 KB

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