Merge pull request #2570 from poolifier/dependabot/npm_and_yarn/regular-e1612e3888
[poolifier.git] / src / queues / fixed-priority-queue.ts
CommitLineData
c6dd1aeb 1import type { IFixedQueue } from './queue-types.js'
f8d5d8fd 2
97231086
JB
3import { AbstractFixedQueue } from './abstract-fixed-queue.js'
4
eadb37e2
JB
5/**
6 * Fixed priority queue.
eadb37e2
JB
7 * @typeParam T - Type of fixed priority queue data.
8 * @internal
9 */
840270a0
JB
10export class FixedPriorityQueue<T>
11 extends AbstractFixedQueue<T>
12 implements IFixedQueue<T> {
097dea68 13 /** @inheritdoc */
f8d5d8fd
JB
14 public enqueue (data: T, priority?: number): number {
15 if (this.full()) {
9008a966 16 throw new Error('Fixed priority queue is full')
f8d5d8fd
JB
17 }
18 priority = priority ?? 0
19 let inserted = false
097dea68
JB
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
3451940f 31 }
f8d5d8fd
JB
32 }
33 if (!inserted) {
34 let index = this.start + this.size
9df282a0
JB
35 if (index >= this.capacity) {
36 index -= this.capacity
f8d5d8fd
JB
37 }
38 this.nodeArray[index] = { data, priority }
39 }
10b1b252 40 return ++this.size
f8d5d8fd 41 }
f8d5d8fd 42}