Commit | Line | Data |
---|---|---|
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 | */ |
8 | export class Queue<T> { | |
9 | private items: Record<number, T> | |
10 | private head: number | |
11 | private tail: number | |
6b27d407 | 12 | private max: number |
29ee7e9a | 13 | |
4d8bf9e4 | 14 | public constructor () { |
29ee7e9a JB |
15 | this.items = {} |
16 | this.head = 0 | |
17 | this.tail = 0 | |
6b27d407 | 18 | this.max = 0 |
29ee7e9a JB |
19 | } |
20 | ||
a0d41544 JB |
21 | /** |
22 | * Get the size of the queue. | |
23 | * | |
24 | * @returns The size of the queue. | |
25 | * @readonly | |
26 | */ | |
4d8bf9e4 JB |
27 | public get size (): number { |
28 | return this.tail - this.head | |
29 | } | |
30 | ||
6b27d407 JB |
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 | ||
a0d41544 JB |
41 | /** |
42 | * Enqueue an item. | |
43 | * | |
44 | * @param item - Item to enqueue. | |
45 | * @returns The new size of the queue. | |
46 | */ | |
4d8bf9e4 | 47 | public enqueue (item: T): number { |
29ee7e9a JB |
48 | this.items[this.tail] = item |
49 | this.tail++ | |
6b27d407 | 50 | if (this.size > this.max) this.max = this.size |
4d8bf9e4 | 51 | return this.size |
29ee7e9a JB |
52 | } |
53 | ||
a0d41544 JB |
54 | /** |
55 | * Dequeue an item. | |
56 | * | |
c318eb2f | 57 | * @returns The dequeued item or `undefined` if the queue is empty. |
a0d41544 | 58 | */ |
4d8bf9e4 JB |
59 | public dequeue (): T | undefined { |
60 | if (this.size <= 0) return undefined | |
29ee7e9a JB |
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 | } | |
49be33fe JB |
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 | } | |
29ee7e9a | 79 | } |