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 | |
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 | * | |
c318eb2f | 44 | * @returns The dequeued item or `undefined` if the queue is empty. |
a0d41544 | 45 | */ |
4d8bf9e4 JB |
46 | public dequeue (): T | undefined { |
47 | if (this.size <= 0) return undefined | |
29ee7e9a JB |
48 | const item = this.items[this.head] |
49 | // eslint-disable-next-line @typescript-eslint/no-dynamic-delete | |
50 | delete this.items[this.head] | |
51 | this.head++ | |
52 | if (this.head === this.tail) { | |
53 | this.head = 0 | |
54 | this.tail = 0 | |
55 | } | |
56 | return item | |
57 | } | |
49be33fe JB |
58 | |
59 | /** | |
60 | * Peek at the first item. | |
61 | */ | |
62 | public peek (): T | undefined { | |
63 | if (this.size <= 0) return undefined | |
64 | return this.items[this.head] | |
65 | } | |
29ee7e9a | 66 | } |