fix: fix priority queue iterator
[poolifier.git] / src / fixed-priority-queue.ts
index 2424b652033d42ee2dad7538a09b64621b60a4ae..3b767eb8b93971b77663f22bf495f353eb830c5a 100644 (file)
@@ -4,12 +4,12 @@
 export const defaultQueueSize = 2048
 
 /**
- * Priority queue node.
+ * Fixed priority queue node.
  *
  * @typeParam T - Type of priority queue node data.
  * @internal
  */
-interface PriorityQueueNode<T> {
+export interface FixedPriorityQueueNode<T> {
   data: T
   priority: number
 }
@@ -22,7 +22,7 @@ interface PriorityQueueNode<T> {
  */
 export class FixedPriorityQueue<T> {
   private start!: number
-  private readonly nodeArray: Array<PriorityQueueNode<T>>
+  private readonly nodeArray: Array<FixedPriorityQueueNode<T>>
   public readonly capacity: number
   public size!: number
   public maxSize!: number
@@ -36,7 +36,7 @@ export class FixedPriorityQueue<T> {
   constructor (size: number = defaultQueueSize) {
     this.checkSize(size)
     this.capacity = size
-    this.nodeArray = new Array<PriorityQueueNode<T>>(this.capacity)
+    this.nodeArray = new Array<FixedPriorityQueueNode<T>>(this.capacity)
     this.clear()
   }
 
@@ -95,6 +95,23 @@ export class FixedPriorityQueue<T> {
     return this.incrementSize()
   }
 
+  /**
+   * Gets data from the fixed priority queue.
+   *
+   * @param index - The index of the data to get.
+   * @returns The data at the index or `undefined` if the fixed priority queue is empty or the index is out of bounds.
+   */
+  public get (index: number): T | undefined {
+    if (this.empty() || index >= this.size) {
+      return undefined
+    }
+    index += this.start
+    if (index >= this.capacity) {
+      index -= this.capacity
+    }
+    return this.nodeArray[index].data
+  }
+
   /**
    * Dequeue data from the fixed priority queue.
    *