-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.ts
78 lines (70 loc) · 1.92 KB
/
utils.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
// The most of this code is ported from https://deno.land/x/[email protected]/mod.ts
// export type Predicate<T> = (value: unknown) => value is T;
export const isNone = (value: unknown): value is undefined | null =>
value === null || value === undefined;
export const isString = (value: unknown): value is string =>
typeof value === "string";
// export function isNumber(value: unknown): value is number {
// return typeof value === "number";
// }
// export function isArray<T extends unknown>(
// value: unknown,
// predicate?: Predicate<T>,
// ): value is T[] {
// return Array.isArray(value) && (!predicate || value.every(predicate));
// }
// export function ensureArray<T>(
// value: unknown,
// predicate?: Predicate<T>,
// ): asserts value is Array<T> {
// if (isArray(value, predicate)) return;
// throw TypeError("value must be an Array");
// }
export type OneByOneResult<T> = {
state: "fulfilled";
value: T;
} | {
state: "rejected";
reason: unknown;
};
/** Promiseを解決した順に返す函数 */
export async function* oneByOne<T>(
promises: Iterable<Promise<T>>,
): AsyncGenerator<OneByOneResult<T>, void, unknown> {
const queue = [] as OneByOneResult<T>[];
let resolve: ((item: OneByOneResult<T>) => void) | undefined;
const push = (item: OneByOneResult<T>) => {
if (!resolve) {
queue.push(item);
return;
}
resolve(item);
resolve = undefined;
};
const pop = () => {
if (queue.length > 0) {
return Promise.resolve(queue.pop()!);
}
return new Promise<OneByOneResult<T>>((res) => resolve = res);
};
let count = 0;
for (const promise of promises) {
promise
.then((value) =>
push({
state: "fulfilled",
value,
})
)
.catch((reason) =>
push({
state: "rejected",
reason,
})
);
count++;
}
for (let i = 0; i < count; i++) {
yield await pop();
}
}