esnext.iterator.reduce.js 985 B

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