feat: expose pool information
[poolifier.git] / src / queue.ts
1 // Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
2
3 /**
4 * Queue
5 *
6 * @typeParam T - Type of queue items.
7 */
8 export class Queue<T> {
9 private items: Record<number, T>
10 private head: number
11 private tail: number
12 private max: number
13
14 public constructor () {
15 this.items = {}
16 this.head = 0
17 this.tail = 0
18 this.max = 0
19 }
20
21 /**
22 * Get the size of the queue.
23 *
24 * @returns The size of the queue.
25 * @readonly
26 */
27 public get size (): number {
28 return this.tail - this.head
29 }
30
31 /**
32 * Get the maximum size of the queue.
33 *
34 * @returns The maximum size of the queue.
35 * @readonly
36 */
37 public get maxSize (): number {
38 return this.max
39 }
40
41 /**
42 * Enqueue an item.
43 *
44 * @param item - Item to enqueue.
45 * @returns The new size of the queue.
46 */
47 public enqueue (item: T): number {
48 this.items[this.tail] = item
49 this.tail++
50 if (this.size > this.max) this.max = this.size
51 return this.size
52 }
53
54 /**
55 * Dequeue an item.
56 *
57 * @returns The dequeued item or `undefined` if the queue is empty.
58 */
59 public dequeue (): T | undefined {
60 if (this.size <= 0) return undefined
61 const item = this.items[this.head]
62 // eslint-disable-next-line @typescript-eslint/no-dynamic-delete
63 delete this.items[this.head]
64 this.head++
65 if (this.head === this.tail) {
66 this.head = 0
67 this.tail = 0
68 }
69 return item
70 }
71
72 /**
73 * Peek at the first item.
74 */
75 public peek (): T | undefined {
76 if (this.size <= 0) return undefined
77 return this.items[this.head]
78 }
79 }