From 2d13278159e318955ea9bc144366023ffd2e4df8 Mon Sep 17 00:00:00 2001 From: Dolan Murvihill Date: Thu, 1 Feb 2024 21:27:37 -0800 Subject: [PATCH] Reverse findIndex for queuing tasks in acquire() --- src/Semaphore.ts | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/src/Semaphore.ts b/src/Semaphore.ts index 2a457c3..21f756c 100644 --- a/src/Semaphore.ts +++ b/src/Semaphore.ts @@ -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(); }); @@ -151,4 +151,13 @@ function insertSorted(a: T[], v: T) { } } +function findIndexFromEnd(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;