-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
esnext.async-iterator.flat-map.js
67 lines (62 loc) · 2.42 KB
/
esnext.async-iterator.flat-map.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
'use strict';
// https://github.com/tc39/proposal-iterator-helpers
var $ = require('../internals/export');
var aFunction = require('../internals/a-function');
var anObject = require('../internals/an-object');
var createAsyncIteratorProxy = require('../internals/async-iterator-create-proxy');
var getAsyncIteratorMethod = require('../internals/get-async-iterator-method');
var AsyncIteratorProxy = createAsyncIteratorProxy(function (arg, Promise) {
var state = this;
var mapper = state.mapper;
var innerIterator, iteratorMethod;
return new Promise(function (resolve, reject) {
var outerLoop = function () {
try {
Promise.resolve(anObject(state.next.call(state.iterator, arg))).then(function (step) {
try {
if (anObject(step).done) {
state.done = true;
resolve({ done: true, value: undefined });
} else {
Promise.resolve(mapper(step.value)).then(function (mapped) {
try {
iteratorMethod = getAsyncIteratorMethod(mapped);
if (iteratorMethod !== undefined) {
state.innerIterator = innerIterator = anObject(iteratorMethod.call(mapped));
state.innerNext = aFunction(innerIterator.next);
return innerLoop();
} reject(TypeError('.flatMap callback should return an iterable object'));
} catch (error2) { reject(error2); }
}, reject);
}
} catch (error1) { reject(error1); }
}, reject);
} catch (error) { reject(error); }
};
var innerLoop = function () {
if (innerIterator = state.innerIterator) {
try {
Promise.resolve(anObject(state.innerNext.call(innerIterator))).then(function (result) {
try {
if (anObject(result).done) {
state.innerIterator = state.innerNext = null;
outerLoop();
} else resolve({ done: false, value: result.value });
} catch (error1) { reject(error1); }
}, reject);
} catch (error) { reject(error); }
} else outerLoop();
};
innerLoop();
});
});
$({ target: 'AsyncIterator', proto: true, real: true }, {
flatMap: function flatMap(mapper) {
return new AsyncIteratorProxy({
iterator: anObject(this),
mapper: aFunction(mapper),
innerIterator: null,
innerNext: null
});
}
});