-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
59 lines (53 loc) · 1.66 KB
/
index.ts
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
/**
* @module @promises/times-parallel
* @copyright © 2017 Yisrael Eliav <[email protected]> (https://github.com/yisraelx)
* @license MIT
*/
import { IOptionalPromise } from '@promises/interfaces';
/**
* @function
* @example
*
* let times: number = 3;
*
* timesParallel(times, (time: number) => {
* let ms = (times-time) * 3;
* return timeout((resolve) => {
* console.log(time);
* resolve(ms);
* }, ms);
* }).then((result: number[]) => {
* console.log(result);
* });
*
* // => 2
* // => 1
* // => 0
* // => [9, 6, 3]
*/
function timesParallel<T extends any[]>(times: IOptionalPromise<number>, fn: (time: number) => IOptionalPromise<T[keyof T & number]>, limit?: number): Promise<T> {
return Promise.resolve(times).then((times) => {
return new Promise((resolve, reject) => {
if (!times || times <= 0) return resolve([]);
let result = Array(times);
limit = limit && limit > 0 && limit < times ? limit : times;
let index: number = 0;
let completed: number = 0;
let each = (thisIndex: number) => {
Promise.resolve(thisIndex).then(fn).then((value) => {
result[thisIndex] = value;
completed++;
if (index < times) {
each(index++);
} else if (completed === times) {
resolve(result);
}
}).catch(reject);
};
while (index < limit) {
each(index++);
}
});
}) as Promise<T>;
}
export default timesParallel;