docs: add comments in queue implementation
[poolifier.git] / src / queue.ts
CommitLineData
13455ed2
JB
1// Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
2
29ee7e9a
JB
3/**
4 * Queue
a0d41544
JB
5 *
6 * @typeParam T - Type of queue items.
29ee7e9a
JB
7 */
8export class Queue<T> {
9 private items: Record<number, T>
10 private head: number
11 private tail: number
12
4d8bf9e4 13 public constructor () {
29ee7e9a
JB
14 this.items = {}
15 this.head = 0
16 this.tail = 0
17 }
18
a0d41544
JB
19 /**
20 * Get the size of the queue.
21 *
22 * @returns The size of the queue.
23 * @readonly
24 */
4d8bf9e4
JB
25 public get size (): number {
26 return this.tail - this.head
27 }
28
a0d41544
JB
29 /**
30 * Enqueue an item.
31 *
32 * @param item - Item to enqueue.
33 * @returns The new size of the queue.
34 */
4d8bf9e4 35 public enqueue (item: T): number {
29ee7e9a
JB
36 this.items[this.tail] = item
37 this.tail++
4d8bf9e4 38 return this.size
29ee7e9a
JB
39 }
40
a0d41544
JB
41 /**
42 * Dequeue an item.
43 *
44 * @returns The dequeued item.
45 * @returns `undefined` if the queue is empty.
46 */
4d8bf9e4
JB
47 public dequeue (): T | undefined {
48 if (this.size <= 0) return undefined
29ee7e9a
JB
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 }
29ee7e9a 59}