Skip to content

Commit

Permalink
#208 - review fixes - add test case, update setPriority method
Browse files Browse the repository at this point in the history
  • Loading branch information
RaishavHanspal committed Jul 18, 2024
1 parent a60bfc1 commit cafe886
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 4 deletions.
13 changes: 9 additions & 4 deletions source/priority-queue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,11 @@ export default class PriorityQueue implements Queue<RunFunction, PriorityQueueOp

const element = {
priority: options.priority,
id: options.id,
run,
};

if (this.size && this.#queue[this.size - 1]!.priority! >= options.priority!) {
if (this.size === 0 || this.#queue[this.size - 1]!.priority! >= options.priority!) {
this.#queue.push(element);
return;
}
Expand All @@ -32,15 +33,19 @@ export default class PriorityQueue implements Queue<RunFunction, PriorityQueueOp
this.#queue.splice(index, 0, element);
}

setPriority(id: string, priority?: number) {
setPriority(id: string, priority: number) {
const existingIndex: number = this.#queue.findIndex((element: Readonly<PriorityQueueOptions>) => 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;
}
Expand Down
20 changes: 20 additions & 0 deletions test/test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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, ['🐌', '🐒', 'πŸ¦†']);
});

0 comments on commit cafe886

Please sign in to comment.