refactor: strict mode in js files
[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> {
116a8c86
JB
9 private items: T[]
10 private offset: number
11 public size: number
12 public maxSize: number
29ee7e9a 13
4d8bf9e4 14 public constructor () {
116a8c86 15 this.items = []
44b3657c 16 this.offset = 0
116a8c86
JB
17 /** The size of the queue. */
18 this.size = 0
116a8c86
JB
19 /** The maximum size of the queue. */
20 this.maxSize = 0
6b27d407
JB
21 }
22
a0d41544
JB
23 /**
24 * Enqueue an item.
25 *
26 * @param item - Item to enqueue.
27 * @returns The new size of the queue.
28 */
4d8bf9e4 29 public enqueue (item: T): number {
116a8c86
JB
30 this.items.push(item)
31 ++this.size
32 if (this.size > this.maxSize) {
33 this.maxSize = this.size
34 }
4d8bf9e4 35 return this.size
29ee7e9a
JB
36 }
37
a0d41544
JB
38 /**
39 * Dequeue an item.
40 *
c318eb2f 41 * @returns The dequeued item or `undefined` if the queue is empty.
a0d41544 42 */
4d8bf9e4 43 public dequeue (): T | undefined {
116a8c86
JB
44 if (this.size <= 0) {
45 return undefined
29ee7e9a 46 }
116a8c86
JB
47 const item = this.items[this.offset]
48 if (++this.offset * 2 >= this.items.length) {
49 this.items = this.items.slice(this.offset)
50 this.offset = 0
51 }
52 --this.size
29ee7e9a
JB
53 return item
54 }
49be33fe
JB
55
56 /**
57 * Peek at the first item.
116a8c86
JB
58 *
59 * @returns The first item or `undefined` if the queue is empty.
49be33fe
JB
60 */
61 public peek (): T | undefined {
116a8c86
JB
62 if (this.size <= 0) {
63 return undefined
64 }
65 return this.items[this.offset]
49be33fe 66 }
df593701
JB
67
68 /**
69 * Clear the queue.
70 */
71 public clear (): void {
72 this.items = []
73 this.offset = 0
74 this.size = 0
75 this.maxSize = 0
76 }
29ee7e9a 77}