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