Skip to content

Commit

Permalink
Reverse findIndex for queuing tasks in acquire()
Browse files Browse the repository at this point in the history
  • Loading branch information
dmurvihill committed Feb 2, 2024
1 parent c546c3f commit 2d13278
Showing 1 changed file with 13 additions and 4 deletions.
17 changes: 13 additions & 4 deletions src/Semaphore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,14 +26,14 @@ class Semaphore implements SemaphoreInterface {

return new Promise((resolve, reject) => {
const task: QueueEntry = { resolve, reject, weight, priority };
const i = this._queue.findIndex((other) => priority > other.priority);
if (i === 0 && weight <= this._value) {
const i = findIndexFromEnd(this._queue, (other) => priority <= other.priority);
if (i === -1 && weight <= this._value) {
// Needs immediate dispatch, skip the queue
this._dispatchItem(task);
} else if (i === -1) {
this._queue.push(task);
this._queue.splice(0, 0, task);
} else {
this._queue.splice(i, 0, task);
this._queue.splice(i + 1, 0, task);
}
this._dispatchQueue();
});
Expand Down Expand Up @@ -151,4 +151,13 @@ function insertSorted<T extends Priority>(a: T[], v: T) {
}
}

function findIndexFromEnd<T>(a: T[], predicate: (e: T) => boolean): number {
for (let i = a.length - 1; i >= 0; i--) {
if (predicate(a[i])) {
return i;
}
}
return -1;
}

export default Semaphore;

0 comments on commit 2d13278

Please sign in to comment.