esnext.iterator.reduce.js 854 B

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