es.iterator.reduce.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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 iteratorClose = require('../internals/iterator-close');
  8. var iteratorHelperWithoutClosingOnEarlyError = require('../internals/iterator-helper-without-closing-on-early-error');
  9. var apply = require('../internals/function-apply');
  10. var fails = require('../internals/fails');
  11. var $TypeError = TypeError;
  12. // https://bugs.webkit.org/show_bug.cgi?id=291651
  13. var FAILS_ON_INITIAL_UNDEFINED = fails(function () {
  14. // eslint-disable-next-line es/no-iterator-prototype-reduce, es/no-array-prototype-keys, array-callback-return -- required for testing
  15. [].keys().reduce(function () { /* empty */ }, undefined);
  16. });
  17. var reduceWithoutClosingOnEarlyError = !FAILS_ON_INITIAL_UNDEFINED && iteratorHelperWithoutClosingOnEarlyError('reduce', $TypeError);
  18. // `Iterator.prototype.reduce` method
  19. // https://tc39.es/ecma262/#sec-iterator.prototype.reduce
  20. $({ target: 'Iterator', proto: true, real: true, forced: FAILS_ON_INITIAL_UNDEFINED || reduceWithoutClosingOnEarlyError }, {
  21. reduce: function reduce(reducer /* , initialValue */) {
  22. anObject(this);
  23. try {
  24. aCallable(reducer);
  25. } catch (error) {
  26. iteratorClose(this, 'throw', error);
  27. }
  28. var noInitial = arguments.length < 2;
  29. var accumulator = noInitial ? undefined : arguments[1];
  30. if (reduceWithoutClosingOnEarlyError) {
  31. return apply(reduceWithoutClosingOnEarlyError, this, noInitial ? [reducer] : [reducer, accumulator]);
  32. }
  33. var record = getIteratorDirect(this);
  34. var counter = 0;
  35. iterate(record, function (value) {
  36. if (noInitial) {
  37. noInitial = false;
  38. accumulator = value;
  39. } else {
  40. accumulator = reducer(accumulator, value, counter);
  41. }
  42. counter++;
  43. }, { IS_RECORD: true });
  44. if (noInitial) throw new $TypeError('Reduce of empty iterator with no initial value');
  45. return accumulator;
  46. }
  47. });