refactor: cleanup queue API
[poolifier.git] / src / queue.ts
CommitLineData
29ee7e9a
JB
1/**
2 * Queue
3 */
4export class Queue<T> {
5 private items: Record<number, T>
6 private head: number
7 private tail: number
8
4d8bf9e4 9 public constructor () {
29ee7e9a
JB
10 this.items = {}
11 this.head = 0
12 this.tail = 0
13 }
14
4d8bf9e4
JB
15 public get size (): number {
16 return this.tail - this.head
17 }
18
19 public enqueue (item: T): number {
29ee7e9a
JB
20 this.items[this.tail] = item
21 this.tail++
4d8bf9e4 22 return this.size
29ee7e9a
JB
23 }
24
4d8bf9e4
JB
25 public dequeue (): T | undefined {
26 if (this.size <= 0) return undefined
29ee7e9a
JB
27 const item = this.items[this.head]
28 // eslint-disable-next-line @typescript-eslint/no-dynamic-delete
29 delete this.items[this.head]
30 this.head++
31 if (this.head === this.tail) {
32 this.head = 0
33 this.tail = 0
34 }
35 return item
36 }
29ee7e9a 37}