| 1 | // Copyright Jerome Benoit. 2021-2023. All Rights Reserved. |
| 2 | |
| 3 | /** |
| 4 | * Queue |
| 5 | */ |
| 6 | export class Queue<T> { |
| 7 | private items: Record<number, T> |
| 8 | private head: number |
| 9 | private tail: number |
| 10 | |
| 11 | public constructor () { |
| 12 | this.items = {} |
| 13 | this.head = 0 |
| 14 | this.tail = 0 |
| 15 | } |
| 16 | |
| 17 | public get size (): number { |
| 18 | return this.tail - this.head |
| 19 | } |
| 20 | |
| 21 | public enqueue (item: T): number { |
| 22 | this.items[this.tail] = item |
| 23 | this.tail++ |
| 24 | return this.size |
| 25 | } |
| 26 | |
| 27 | public dequeue (): T | undefined { |
| 28 | if (this.size <= 0) return undefined |
| 29 | const item = this.items[this.head] |
| 30 | // eslint-disable-next-line @typescript-eslint/no-dynamic-delete |
| 31 | delete this.items[this.head] |
| 32 | this.head++ |
| 33 | if (this.head === this.tail) { |
| 34 | this.head = 0 |
| 35 | this.tail = 0 |
| 36 | } |
| 37 | return item |
| 38 | } |
| 39 | } |