refactor: add a new async queue
This commit is contained in:
@@ -0,0 +1,32 @@
|
||||
export class AsyncQueue<T> {
|
||||
private items: T[] = [];
|
||||
private resolvers: ((value: T) => void)[] = [];
|
||||
|
||||
push(item: T): void {
|
||||
if (this.resolvers.length > 0) {
|
||||
const resolve = this.resolvers.shift()!;
|
||||
resolve(item);
|
||||
} else {
|
||||
this.items.push(item);
|
||||
}
|
||||
}
|
||||
|
||||
pushAll(items: Iterable<T>): void {
|
||||
for (const item of items) {
|
||||
this.push(item);
|
||||
}
|
||||
}
|
||||
|
||||
async pop(): Promise<T> {
|
||||
if (this.items.length > 0) {
|
||||
return this.items.shift()!;
|
||||
}
|
||||
return new Promise<T>((resolve) => {
|
||||
this.resolvers.push(resolve);
|
||||
});
|
||||
}
|
||||
|
||||
get length(): number {
|
||||
return this.items.length - this.resolvers.length;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user