X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=src%2Fpriority-queue.ts;h=e68fe37d16e732efc907562adbb9716b9793c612;hb=910416386b4f7d0da4e6f0d8551cefa2539c5ced;hp=3c26ff35208b6f0ef599158ff6d446f47a1e8123;hpb=95d1a734d57942c892202df7c0fcaf2fb5ab89ab;p=poolifier.git diff --git a/src/priority-queue.ts b/src/priority-queue.ts index 3c26ff35..e68fe37d 100644 --- a/src/priority-queue.ts +++ b/src/priority-queue.ts @@ -26,10 +26,17 @@ export class PriorityQueue { /** The maximum size of the priority queue. */ public maxSize!: number + /** + * The number of filled prioritized buckets. + */ + public get buckets (): number { + return this.k === Infinity ? 1 : Math.trunc(this.nodeArray.length / this.k) + } + /** * Constructs a priority queue. * - * @param k - Prioritized bucket size. + * @param k - Prioritized bucket size. @defaultValue Infinity */ public constructor (k = Infinity) { if (k !== Infinity && !Number.isSafeInteger(k)) { @@ -51,10 +58,7 @@ export class PriorityQueue { */ public enqueue (data: T, priority?: number): number { priority = priority ?? 0 - const startIndex = - this.k === Infinity || this.nodeArray.length / this.k < 1 - ? 0 - : Math.trunc(this.nodeArray.length / this.k) * this.k + const startIndex = this.k === Infinity ? 0 : this.buckets * this.k let inserted = false for (let index = startIndex; index < this.nodeArray.length; index++) { if (this.nodeArray[index].priority > priority) { @@ -87,9 +91,7 @@ export class PriorityQueue { --bucket } } - if (this.size > 0) { - --this.size - } + this.decrementSize() return this.nodeArray.shift()?.data } @@ -121,7 +123,7 @@ export class PriorityQueue { /** * Returns an iterator for the priority queue. * - * @returns An iterator for the deque. + * @returns An iterator for the priority queue. * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols */ [Symbol.iterator] (): Iterator { @@ -156,4 +158,16 @@ export class PriorityQueue { } return this.size } + + /** + * Decrements the size of the priority queue. + * + * @returns The new size of the priority queue. + */ + private decrementSize (): number { + if (this.size > 0) { + --this.size + } + return this.size + } }