refactor: move queueing code into its own directory
[poolifier.git] / src / queues / fixed-priority-queue.ts
1 import { AbstractFixedQueue } from './abstract-fixed-queue.js'
2 import type { IFixedQueue } from './queue-types.js'
3
4 /**
5 * Fixed priority queue.
6 * @typeParam T - Type of fixed priority queue data.
7 * @internal
8 */
9 export class FixedPriorityQueue<T>
10 extends AbstractFixedQueue<T>
11 implements IFixedQueue<T> {
12 /** @inheritdoc */
13 public enqueue (data: T, priority?: number): number {
14 if (this.full()) {
15 throw new Error('Fixed priority queue is full')
16 }
17 priority = priority ?? 0
18 let inserted = false
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
30 }
31 }
32 if (!inserted) {
33 let index = this.start + this.size
34 if (index >= this.capacity) {
35 index -= this.capacity
36 }
37 this.nodeArray[index] = { data, priority }
38 }
39 return ++this.size
40 }
41 }