UNPKG

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