From: Jérôme Benoit Date: Tue, 28 May 2024 19:01:19 +0000 (+0200) Subject: fix: fix priority queue iterator X-Git-Tag: v4.0.13~5 X-Git-Url: https://git.piment-noir.org/?a=commitdiff_plain;h=1d98bad2cdcfd3c3d6ceb2707faffa98391237c6;p=poolifier.git fix: fix priority queue iterator Signed-off-by: Jérôme Benoit --- diff --git a/src/fixed-priority-queue.ts b/src/fixed-priority-queue.ts index b50853dd..3b767eb8 100644 --- a/src/fixed-priority-queue.ts +++ b/src/fixed-priority-queue.ts @@ -95,6 +95,23 @@ export class FixedPriorityQueue { 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. * diff --git a/src/priority-queue.ts b/src/priority-queue.ts index 142fa5e8..ce96b4e8 100644 --- a/src/priority-queue.ts +++ b/src/priority-queue.ts @@ -95,22 +95,25 @@ export class PriorityQueue { */ public dequeue (bucket?: number): T | undefined { let tail: PriorityQueueNode | undefined = this.tail - if (bucket != null) { - let currentBucket = 0 + let tailChanged = false + if (bucket != null && bucket > 0) { + let currentBucket = 1 while (tail != null) { - ++currentBucket if (currentBucket === bucket) { break } + ++currentBucket tail = tail.next + tailChanged = true } } // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const data = tail!.dequeue() // eslint-disable-next-line @typescript-eslint/no-non-null-assertion if (tail!.empty() && tail!.next != null) { - if (tail === this.tail) { - this.tail = tail.next + if (!tailChanged) { + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + this.tail = tail!.next } else { let node: PriorityQueueNode | undefined = this.tail while (node != null) { @@ -143,21 +146,21 @@ export class PriorityQueue { * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols */ public [Symbol.iterator] (): Iterator { - let i = 0 + let index = 0 let node = this.tail return { next: () => { - if (node.empty() || (i >= node.capacity && node.next == null)) { + const value = node.get(index) as T + if (value == null) { return { value: undefined, done: true } } - const value = node.dequeue() as T - ++i - if (i === node.capacity && node.next != null) { + ++index + if (index === node.capacity && node.next != null) { node = node.next - i = 0 + index = 0 } return { value,