async-iterator-iteration.js
2.4 KB
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
68
69
70
71
72
73
74
75
76
77
78
79
80
'use strict';
// https://github.com/tc39/proposal-iterator-helpers
var aFunction = require('../internals/a-function');
var anObject = require('../internals/an-object');
var getBuiltIn = require('../internals/get-built-in');
var Promise = getBuiltIn('Promise');
var push = [].push;
var createMethod = function (TYPE) {
var IS_TO_ARRAY = TYPE == 0;
var IS_FOR_EACH = TYPE == 1;
var IS_EVERY = TYPE == 2;
var IS_SOME = TYPE == 3;
return function (iterator, fn) {
anObject(iterator);
var next = aFunction(iterator.next);
var array = IS_TO_ARRAY ? [] : undefined;
if (!IS_TO_ARRAY) aFunction(fn);
return new Promise(function (resolve, reject) {
var closeIteration = function (method, argument) {
try {
var returnMethod = iterator['return'];
if (returnMethod !== undefined) {
return Promise.resolve(returnMethod.call(iterator)).then(function () {
method(argument);
}, function (error) {
reject(error);
});
}
} catch (error2) {
return reject(error2);
} method(argument);
};
var onError = function (error) {
closeIteration(reject, error);
};
var loop = function () {
try {
Promise.resolve(anObject(next.call(iterator))).then(function (step) {
try {
if (anObject(step).done) {
resolve(IS_TO_ARRAY ? array : IS_SOME ? false : IS_EVERY || undefined);
} else {
var value = step.value;
if (IS_TO_ARRAY) {
push.call(array, value);
loop();
} else {
Promise.resolve(fn(value)).then(function (result) {
if (IS_FOR_EACH) {
loop();
} else if (IS_EVERY) {
result ? loop() : closeIteration(resolve, false);
} else {
result ? closeIteration(resolve, IS_SOME || value) : loop();
}
}, onError);
}
}
} catch (error) { onError(error); }
}, onError);
} catch (error2) { onError(error2); }
};
loop();
});
};
};
module.exports = {
toArray: createMethod(0),
forEach: createMethod(1),
every: createMethod(2),
some: createMethod(3),
find: createMethod(4)
};