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