1 | 'use strict';
|
---|
2 | var $ = require('../internals/export');
|
---|
3 | var call = require('../internals/function-call');
|
---|
4 | var aCallable = require('../internals/a-callable');
|
---|
5 | var anObject = require('../internals/an-object');
|
---|
6 | var isObject = require('../internals/is-object');
|
---|
7 | var getBuiltIn = require('../internals/get-built-in');
|
---|
8 | var getIteratorDirect = require('../internals/get-iterator-direct');
|
---|
9 | var closeAsyncIteration = require('../internals/async-iterator-close');
|
---|
10 |
|
---|
11 | var Promise = getBuiltIn('Promise');
|
---|
12 | var $TypeError = TypeError;
|
---|
13 |
|
---|
14 | // `AsyncIterator.prototype.reduce` method
|
---|
15 | // https://github.com/tc39/proposal-async-iterator-helpers
|
---|
16 | $({ target: 'AsyncIterator', proto: true, real: true }, {
|
---|
17 | reduce: function reduce(reducer /* , initialValue */) {
|
---|
18 | anObject(this);
|
---|
19 | aCallable(reducer);
|
---|
20 | var record = getIteratorDirect(this);
|
---|
21 | var iterator = record.iterator;
|
---|
22 | var next = record.next;
|
---|
23 | var noInitial = arguments.length < 2;
|
---|
24 | var accumulator = noInitial ? undefined : arguments[1];
|
---|
25 | var counter = 0;
|
---|
26 |
|
---|
27 | return new Promise(function (resolve, reject) {
|
---|
28 | var ifAbruptCloseAsyncIterator = function (error) {
|
---|
29 | closeAsyncIteration(iterator, reject, error, reject);
|
---|
30 | };
|
---|
31 |
|
---|
32 | var loop = function () {
|
---|
33 | try {
|
---|
34 | Promise.resolve(anObject(call(next, iterator))).then(function (step) {
|
---|
35 | try {
|
---|
36 | if (anObject(step).done) {
|
---|
37 | noInitial ? reject(new $TypeError('Reduce of empty iterator with no initial value')) : resolve(accumulator);
|
---|
38 | } else {
|
---|
39 | var value = step.value;
|
---|
40 | if (noInitial) {
|
---|
41 | noInitial = false;
|
---|
42 | accumulator = value;
|
---|
43 | loop();
|
---|
44 | } else try {
|
---|
45 | var result = reducer(accumulator, value, counter);
|
---|
46 |
|
---|
47 | var handler = function ($result) {
|
---|
48 | accumulator = $result;
|
---|
49 | loop();
|
---|
50 | };
|
---|
51 |
|
---|
52 | if (isObject(result)) Promise.resolve(result).then(handler, ifAbruptCloseAsyncIterator);
|
---|
53 | else handler(result);
|
---|
54 | } catch (error3) { ifAbruptCloseAsyncIterator(error3); }
|
---|
55 | }
|
---|
56 | counter++;
|
---|
57 | } catch (error2) { reject(error2); }
|
---|
58 | }, reject);
|
---|
59 | } catch (error) { reject(error); }
|
---|
60 | };
|
---|
61 |
|
---|
62 | loop();
|
---|
63 | });
|
---|
64 | }
|
---|
65 | });
|
---|