From 1d98bad2cdcfd3c3d6ceb2707faffa98391237c6 Mon Sep 17 00:00:00 2001 From: =?utf8?q?J=C3=A9r=C3=B4me=20Benoit?= Date: Tue, 28 May 2024 21:01:19 +0200 Subject: [PATCH] fix: fix priority queue iterator MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit Signed-off-by: Jérôme Benoit --- src/fixed-priority-queue.ts | 17 +++++++++++++++++ src/priority-queue.ts | 25 ++++++++++++++----------- 2 files changed, 31 insertions(+), 11 deletions(-) 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, -- 2.34.1