-
Notifications
You must be signed in to change notification settings - Fork 70
Expand file tree
/
Copy pathiterator.ts
More file actions
90 lines (78 loc) · 1.98 KB
/
Copy pathiterator.ts
File metadata and controls
90 lines (78 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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import { Options, IterableOutput, OutputIterator } from "../types";
import { Walker } from "./walker";
class WalkerIterator<TOutput extends IterableOutput> {
#resolver?: () => void;
#walker: Walker<TOutput>;
#currentGroup?: string[];
#queue: TOutput[number][] = [];
#error?: unknown;
public constructor(root: string, options: Options) {
const pushPath = options.group ? this.#pushPath : this.#pushResult;
this.#walker = new Walker<TOutput>(
root,
options,
this.#onComplete,
pushPath,
this.#pushResult
);
}
#pushPath = (path: string, arr: string[]) => {
if (arr !== this.#currentGroup) {
this.#currentGroup = arr;
}
arr.push(path);
};
#pushResult = async (result: TOutput[number]) => {
this.#queue.push(result);
if (this.#resolver) {
const resolver = this.#resolver;
this.#resolver = undefined;
resolver();
}
};
#onComplete = (err: unknown) => {
this.#currentGroup = undefined;
this.#complete = true;
if (err) {
this.#error = err;
}
if (this.#resolver) {
const resolver = this.#resolver;
this.#resolver = undefined;
resolver();
}
};
async *start(): OutputIterator<TOutput> {
this.#walker.start();
try {
while (true) {
for (const item of this.#queue) {
if (this.#walker.aborted) {
break;
}
yield item;
}
this.#queue = [];
if (this.#error) {
throw this.#error;
}
if (this.#complete || this.#walker.aborted) {
return;
}
await new Promise<void>((resolve) => {
this.#resolver = resolve;
});
}
} finally {
this.#walker.stop();
}
}
#complete: boolean = false;
}
export function iterator<TOutput extends IterableOutput>(
root: string,
options: Options
): AsyncIterable<TOutput[number]> {
const walker = new WalkerIterator<TOutput>(root, options);
return walker.start();
}