esnext.iterator.reduce.js 947 B

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