fix: fix iteration in fixed queue if start > size
[poolifier.git] / src / fixed-priority-queue.ts
index 60096ce04e9c77da42639420ba4a4a9675b9d2ea..1204cf8153c7a7e8b9b9f4e774f4528ba5e9bdab 100644 (file)
@@ -14,6 +14,12 @@ export interface PriorityQueueNode<T> {
   priority: number
 }
 
+/**
+ * Fixed priority queue.
+ *
+ * @typeParam T - Type of fixed priority queue data.
+ * @internal
+ */
 export class FixedPriorityQueue<T> {
   private start!: number
   private readonly nodeArray: Array<PriorityQueueNode<T>>
@@ -39,18 +45,26 @@ export class FixedPriorityQueue<T> {
       throw new Error('Priority queue is full')
     }
     priority = priority ?? 0
+    const nodeArrayLength = this.nodeArray.length
+    let index = this.start
     let inserted = false
-    for (let index = this.start; index < this.nodeArray.length; index++) {
+    for (let i = 0; i < this.size; i++) {
       if (this.nodeArray[index]?.priority > priority) {
         this.nodeArray.splice(index, 0, { data, priority })
         inserted = true
         break
       }
+      index++
+      if (index === nodeArrayLength) {
+        index = 0
+      }
     }
+    this.nodeArray.length !== nodeArrayLength &&
+      (this.nodeArray.length = nodeArrayLength)
     if (!inserted) {
       let index = this.start + this.size
-      if (index >= this.nodeArray.length) {
-        index -= this.nodeArray.length
+      if (index >= nodeArrayLength) {
+        index -= nodeArrayLength
       }
       this.nodeArray[index] = { data, priority }
     }
@@ -86,7 +100,8 @@ export class FixedPriorityQueue<T> {
    * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols
    */
   [Symbol.iterator] (): Iterator<T> {
-    let i = this.start
+    let index = this.start
+    let i = 0
     return {
       next: () => {
         if (i >= this.size) {
@@ -95,8 +110,12 @@ export class FixedPriorityQueue<T> {
             done: true
           }
         }
-        const value = this.nodeArray[i].data
+        const value = this.nodeArray[index].data
+        index++
         i++
+        if (index === this.nodeArray.length) {
+          index = 0
+        }
         return {
           value,
           done: false
@@ -121,7 +140,7 @@ export class FixedPriorityQueue<T> {
   private checkSize (size: number): void {
     if (!Number.isSafeInteger(size)) {
       throw new TypeError(
-        `Invalid fixed priority queue size: ${size} is not an integer`
+        `Invalid fixed priority queue size: '${size}' is not an integer`
       )
     }
     if (size < 0) {