boardgame-core/src/utils/async-queue.ts

33 lines
669 B
TypeScript
Raw Normal View History

2026-04-02 10:04:22 +08:00
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;
}
}