-
Notifications
You must be signed in to change notification settings - Fork 0
/
extensions.ts
47 lines (43 loc) · 1.49 KB
/
extensions.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
enum AsyncMode {
Sequential, Parellel
}
declare global {
interface Array<T> {
asyncFind(predicate: (this: void, item: T, index: number, obj: T[]) => Promise<any>, mode?: AsyncMode): Promise<T | undefined>
}
}
Array.prototype.asyncFind = async function <T>(
predicate: (this: void, item: T, index: number, obj: T[]) => Promise<any>,
// asyncFind is sequential by default
mode = AsyncMode.Sequential) {
const arr = this as T[];
switch (mode) {
// Avoids flooding the system with requests - minimises resource load
case AsyncMode.Sequential:
{
let index = 0;
for (const item of arr) {
// Fire only the promise in question
if (await predicate(item, index, arr))
return item;
else index++;
}
}
break;
// Doesn't wait for each predicate to resolve - can be much faster
case AsyncMode.Parellel:
{
let index = 0;
// Fire off all promises immediately
const promises = arr.map(predicate);
// One by one, wait for each predicate to be determined
for await (const result of promises) {
// Stop as soon as one matches
if (result) return arr[index];
else index++;
}
}
break;
}
}
export { AsyncMode };