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