docs: add comments in queue implementation
[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
13 public constructor () {
14 this.items = {}
15 this.head = 0
16 this.tail = 0
17 }
18
19 /**
20 * Get the size of the queue.
21 *
22 * @returns The size of the queue.
23 * @readonly
24 */
25 public get size (): number {
26 return this.tail - this.head
27 }
28
29 /**
30 * Enqueue an item.
31 *
32 * @param item - Item to enqueue.
33 * @returns The new size of the queue.
34 */
35 public enqueue (item: T): number {
36 this.items[this.tail] = item
37 this.tail++
38 return this.size
39 }
40
41 /**
42 * Dequeue an item.
43 *
44 * @returns The dequeued item.
45 * @returns `undefined` if the queue is empty.
46 */
47 public dequeue (): T | undefined {
48 if (this.size <= 0) return undefined
49 const item = this.items[this.head]
50 // eslint-disable-next-line @typescript-eslint/no-dynamic-delete
51 delete this.items[this.head]
52 this.head++
53 if (this.head === this.tail) {
54 this.head = 0
55 this.tail = 0
56 }
57 return item
58 }
59 }