| 1 | import type { IFixedQueue } from './queue-types.js' |
| 2 | |
| 3 | import { AbstractFixedQueue } from './abstract-fixed-queue.js' |
| 4 | |
| 5 | /** |
| 6 | * Fixed priority queue. |
| 7 | * @typeParam T - Type of fixed priority queue data. |
| 8 | * @internal |
| 9 | */ |
| 10 | export class FixedPriorityQueue<T> |
| 11 | extends AbstractFixedQueue<T> |
| 12 | implements IFixedQueue<T> { |
| 13 | /** @inheritdoc */ |
| 14 | public enqueue (data: T, priority?: number): number { |
| 15 | if (this.full()) { |
| 16 | throw new Error('Fixed priority queue is full') |
| 17 | } |
| 18 | priority = priority ?? 0 |
| 19 | let inserted = false |
| 20 | let index = this.start |
| 21 | for (let i = 0; i < this.size; i++) { |
| 22 | if (this.nodeArray[index].priority > priority) { |
| 23 | this.nodeArray.splice(index, 0, { data, priority }) |
| 24 | this.nodeArray.length = this.capacity |
| 25 | inserted = true |
| 26 | break |
| 27 | } |
| 28 | ++index |
| 29 | if (index === this.capacity) { |
| 30 | index = 0 |
| 31 | } |
| 32 | } |
| 33 | if (!inserted) { |
| 34 | let index = this.start + this.size |
| 35 | if (index >= this.capacity) { |
| 36 | index -= this.capacity |
| 37 | } |
| 38 | this.nodeArray[index] = { data, priority } |
| 39 | } |
| 40 | return ++this.size |
| 41 | } |
| 42 | } |