-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.ts
More file actions
71 lines (61 loc) · 1.98 KB
/
utils.ts
File metadata and controls
71 lines (61 loc) · 1.98 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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Bentley Systems, Incorporated. All rights reserved.
* See LICENSE.md in the project root for license terms and full copyright notice.
*--------------------------------------------------------------------------------------------*/
export async function* splitBeforeEach<T, U>(
iterable: AsyncIterable<T>,
selector: (value: T) => U,
markers: U[],
): AsyncGenerator<T[]> {
let accumulator: T[] = [];
let currentMarkerIndex = 0;
for await (const value of iterable) {
if (currentMarkerIndex !== markers.length && selector(value) === markers[currentMarkerIndex]) {
yield accumulator;
accumulator = [];
++currentMarkerIndex;
}
accumulator.push(value);
}
yield accumulator;
}
export async function* flatten<T>(iterable: AsyncIterable<T[]>): AsyncGenerator<T> {
for await (const values of iterable) {
for (const value of values) {
yield value;
}
}
}
export async function* map<T, U>(iterable: AsyncIterable<T>, transform: (value: T) => U): AsyncGenerator<U> {
for await (const value of iterable) {
yield transform(value);
}
}
export async function* skip<T>(iterable: AsyncIterable<T>, n: number): AsyncGenerator<T> {
const iterator = iterable[Symbol.asyncIterator]();
for (let i = 0; i < n; ++i) {
const result = await iterator.next();
if (result.done) {
return result.value;
}
}
let result = await iterator.next();
while (!result.done) {
yield result.value;
result = await iterator.next();
}
return result.value;
}
export async function tryXTimes<T>(func: () => Promise<T>, attempts: number, delayInMilliseconds: number = 5000): Promise<T> {
let error: unknown = null;
while (attempts > 0) {
try {
return await func();
} catch (err) {
attempts--;
error = err;
await new Promise((resolve) => setTimeout(resolve, delayInMilliseconds));
}
}
throw error;
}