From 3451940fcbcf9750ad6e702ca296be7f8560408e Mon Sep 17 00:00:00 2001 From: =?utf8?q?J=C3=A9r=C3=B4me=20Benoit?= Date: Sun, 26 May 2024 16:46:04 +0200 Subject: [PATCH] fix: fix iteration in fixed queue if start > size 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 | 16 +++++++++++++--- tests/fixed-priority-queue.test.mjs | 2 +- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/src/fixed-priority-queue.ts b/src/fixed-priority-queue.ts index fadaee75..1204cf81 100644 --- a/src/fixed-priority-queue.ts +++ b/src/fixed-priority-queue.ts @@ -46,13 +46,18 @@ export class FixedPriorityQueue { } priority = priority ?? 0 const nodeArrayLength = this.nodeArray.length + let index = this.start let inserted = false - for (let index = this.start; index < nodeArrayLength; 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) @@ -95,7 +100,8 @@ export class FixedPriorityQueue { * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols */ [Symbol.iterator] (): Iterator { - let i = this.start + let index = this.start + let i = 0 return { next: () => { if (i >= this.size) { @@ -104,8 +110,12 @@ export class FixedPriorityQueue { 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 diff --git a/tests/fixed-priority-queue.test.mjs b/tests/fixed-priority-queue.test.mjs index 7a150690..ef238aef 100644 --- a/tests/fixed-priority-queue.test.mjs +++ b/tests/fixed-priority-queue.test.mjs @@ -8,7 +8,7 @@ // describe('Fixed priority queue test suite', () => { // it('Verify constructor() behavior', () => { // expect(() => new FixedPriorityQueue('')).toThrow( -// new TypeError('Invalid fixed priority queue size: '' is not an integer') +// new TypeError("Invalid fixed priority queue size: '' is not an integer") // ) // expect(() => new FixedPriorityQueue(-1)).toThrow( // new RangeError('Invalid fixed priority queue size: -1 < 0') -- 2.34.1