1 // Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
6 * @typeParam T - Type of queue items.
8 export class Queue
<T
> {
10 private offset
!: number
11 /** The size of the queue. */
13 /** The maximum size of the queue. */
14 public maxSize
!: number
16 public constructor () {
23 * @param item - Item to enqueue.
24 * @returns The new size of the queue.
26 public enqueue (item
: T
): number {
29 if (this.size
> this.maxSize
) {
30 this.maxSize
= this.size
38 * @returns The dequeued item or `undefined` if the queue is empty.
40 public dequeue (): T
| undefined {
44 const item
= this.items
[this.offset
]
45 if (++this.offset
* 2 >= this.items
.length
) {
46 this.items
= this.items
.slice(this.offset
)
54 * Peeks at the first item.
56 * @returns The first item or `undefined` if the queue is empty.
58 public peek (): T
| undefined {
62 return this.items
[this.offset
]
68 public clear (): void {
76 * Returns an iterator for the queue.
78 * @returns An iterator for the queue.
79 * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols
81 [Symbol
.iterator
] (): Iterator
<T
> {
82 const items
= this.items
87 if (i
>= items
.length
) {
93 const value
= items
[i
]