33 lines
669 B
TypeScript
33 lines
669 B
TypeScript
|
|
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;
|
||
|
|
}
|
||
|
|
}
|