From cafe886eada509b899c39bcb7e09846fffb1bce3 Mon Sep 17 00:00:00 2001 From: Raishav Hanspal Date: Thu, 18 Jul 2024 18:55:26 +0530 Subject: [PATCH] #208 - review fixes - add test case, update setPriority method --- source/priority-queue.ts | 13 +++++++++---- test/test.ts | 20 ++++++++++++++++++++ 2 files changed, 29 insertions(+), 4 deletions(-) diff --git a/source/priority-queue.ts b/source/priority-queue.ts index f1115aa..86d1baf 100644 --- a/source/priority-queue.ts +++ b/source/priority-queue.ts @@ -17,10 +17,11 @@ export default class PriorityQueue implements Queue= options.priority!) { + if (this.size === 0 || this.#queue[this.size - 1]!.priority! >= options.priority!) { this.#queue.push(element); return; } @@ -32,15 +33,19 @@ export default class PriorityQueue implements Queue) => element.id === id); + if (existingIndex === -1) { + throw new Error('Invalid Index - No promise function of specified id available in the queue.'); + } + const [item] = this.#queue.splice(existingIndex, 1); if (item === undefined) { return; } - item.priority = priority ?? ((item.priority ?? 0) + 1); - if (this.size && this.#queue[this.size - 1]!.priority! >= priority!) { + item.priority = priority; + if (this.size === 0 || this.#queue[this.size - 1]!.priority! >= priority) { this.#queue.push(item); return; } diff --git a/test/test.ts b/test/test.ts index da828e0..b88efab 100644 --- a/test/test.ts +++ b/test/test.ts @@ -1154,3 +1154,23 @@ test('.setPriority() - execute a promise before planned', async t => { await queue.onIdle(); t.deepEqual(result, ['🐌', '🐢', '🦆']); }); + +test.failing('.setPriority() - with invalid "id"', async t => { + const result: string[] = []; + const queue = new PQueue({concurrency: 1}); + queue.add(async () => { + await delay(400); + result.push('🐌'); + }, {id: '🐌'}); + queue.add(async () => { + await delay(400); + result.push('🦆'); + }, {id: '🦆'}); + queue.add(async () => { + await delay(400); + result.push('🐢'); + }, {id: '🐢'}); + queue.setPriority('⚡️', 1); + await queue.onIdle(); + t.deepEqual(result, ['🐌', '🐢', '🦆']); +});