| 1 | // Copyright Jerome Benoit. 2021-2023. All Rights Reserved. |
| 2 | |
| 3 | /** |
| 4 | * Queue |
| 5 | * |
| 6 | * @typeParam T - Type of queue items. |
| 7 | */ |
| 8 | export class Queue<T> { |
| 9 | private items: T[] |
| 10 | private offset: number |
| 11 | public size: number |
| 12 | public maxSize: number |
| 13 | |
| 14 | public constructor () { |
| 15 | this.items = [] |
| 16 | this.offset = 0 |
| 17 | /** The size of the queue. */ |
| 18 | this.size = 0 |
| 19 | /** The maximum size of the queue. */ |
| 20 | this.maxSize = 0 |
| 21 | } |
| 22 | |
| 23 | /** |
| 24 | * Enqueue an item. |
| 25 | * |
| 26 | * @param item - Item to enqueue. |
| 27 | * @returns The new size of the queue. |
| 28 | */ |
| 29 | public enqueue (item: T): number { |
| 30 | this.items.push(item) |
| 31 | ++this.size |
| 32 | if (this.size > this.maxSize) { |
| 33 | this.maxSize = this.size |
| 34 | } |
| 35 | return this.size |
| 36 | } |
| 37 | |
| 38 | /** |
| 39 | * Dequeue an item. |
| 40 | * |
| 41 | * @returns The dequeued item or `undefined` if the queue is empty. |
| 42 | */ |
| 43 | public dequeue (): T | undefined { |
| 44 | if (this.size <= 0) { |
| 45 | return undefined |
| 46 | } |
| 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 |
| 53 | return item |
| 54 | } |
| 55 | |
| 56 | /** |
| 57 | * Peek at the first item. |
| 58 | * |
| 59 | * @returns The first item or `undefined` if the queue is empty. |
| 60 | */ |
| 61 | public peek (): T | undefined { |
| 62 | if (this.size <= 0) { |
| 63 | return undefined |
| 64 | } |
| 65 | return this.items[this.offset] |
| 66 | } |
| 67 | } |