UNPKG

3.33 kBJavaScriptView Raw
1'use strict';
2// https://github.com/tc39/proposal-iterator-helpers
3// https://github.com/tc39/proposal-array-from-async
4var call = require('../internals/function-call');
5var aCallable = require('../internals/a-callable');
6var anObject = require('../internals/an-object');
7var isObject = require('../internals/is-object');
8var doesNotExceedSafeInteger = require('../internals/does-not-exceed-safe-integer');
9var getBuiltIn = require('../internals/get-built-in');
10var getIteratorDirect = require('../internals/get-iterator-direct');
11var closeAsyncIteration = require('../internals/async-iterator-close');
12
13var createMethod = function (TYPE) {
14 var IS_TO_ARRAY = TYPE === 0;
15 var IS_FOR_EACH = TYPE === 1;
16 var IS_EVERY = TYPE === 2;
17 var IS_SOME = TYPE === 3;
18 return function (object, fn, target) {
19 anObject(object);
20 var MAPPING = fn !== undefined;
21 if (MAPPING || !IS_TO_ARRAY) aCallable(fn);
22 var record = getIteratorDirect(object);
23 var Promise = getBuiltIn('Promise');
24 var iterator = record.iterator;
25 var next = record.next;
26 var counter = 0;
27
28 return new Promise(function (resolve, reject) {
29 var ifAbruptCloseAsyncIterator = function (error) {
30 closeAsyncIteration(iterator, reject, error, reject);
31 };
32
33 var loop = function () {
34 try {
35 if (MAPPING) try {
36 doesNotExceedSafeInteger(counter);
37 } catch (error5) { ifAbruptCloseAsyncIterator(error5); }
38 Promise.resolve(anObject(call(next, iterator))).then(function (step) {
39 try {
40 if (anObject(step).done) {
41 if (IS_TO_ARRAY) {
42 target.length = counter;
43 resolve(target);
44 } else resolve(IS_SOME ? false : IS_EVERY || undefined);
45 } else {
46 var value = step.value;
47 try {
48 if (MAPPING) {
49 var result = fn(value, counter);
50
51 var handler = function ($result) {
52 if (IS_FOR_EACH) {
53 loop();
54 } else if (IS_EVERY) {
55 $result ? loop() : closeAsyncIteration(iterator, resolve, false, reject);
56 } else if (IS_TO_ARRAY) {
57 try {
58 target[counter++] = $result;
59 loop();
60 } catch (error4) { ifAbruptCloseAsyncIterator(error4); }
61 } else {
62 $result ? closeAsyncIteration(iterator, resolve, IS_SOME || value, reject) : loop();
63 }
64 };
65
66 if (isObject(result)) Promise.resolve(result).then(handler, ifAbruptCloseAsyncIterator);
67 else handler(result);
68 } else {
69 target[counter++] = value;
70 loop();
71 }
72 } catch (error3) { ifAbruptCloseAsyncIterator(error3); }
73 }
74 } catch (error2) { reject(error2); }
75 }, reject);
76 } catch (error) { reject(error); }
77 };
78
79 loop();
80 });
81 };
82};
83
84module.exports = {
85 toArray: createMethod(0),
86 forEach: createMethod(1),
87 every: createMethod(2),
88 some: createMethod(3),
89 find: createMethod(4)
90};