X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=src%2Fpriority-queue.ts;h=64b5a9248a804130107b810c412bf4c978ae8cd9;hb=75f30e744551af87736f998db9ad02be7206e89e;hp=cf4fb150e1e1caba20ff9e9d579128c110c40e73;hpb=e41b02718bb9355f7934f0198568cc0ac6f70f9a;p=poolifier.git diff --git a/src/priority-queue.ts b/src/priority-queue.ts index cf4fb150..64b5a924 100644 --- a/src/priority-queue.ts +++ b/src/priority-queue.ts @@ -1,13 +1,18 @@ +// Copyright Jerome Benoit. 2024. All Rights Reserved. + /** + * Priority queue node. + * + * @typeParam T - Type of priority queue node data. * @internal */ -interface PriorityQueueNode { +export interface PriorityQueueNode { data: T priority: number } /** - * k-priority queue. + * Priority queue. * * @typeParam T - Type of priority queue data. * @internal @@ -22,9 +27,9 @@ export class PriorityQueue { public maxSize!: number /** - * Constructs a k-priority queue. + * 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)) { @@ -67,9 +72,21 @@ export class PriorityQueue { /** * Dequeue data from the priority queue. * + * @param bucket - The prioritized bucket to dequeue from. @defaultValue 0 * @returns The dequeued data or `undefined` if the priority queue is empty. */ - public dequeue (): T | undefined { + public dequeue (bucket = 0): T | undefined { + if (this.k !== Infinity && bucket > 0) { + while (bucket > 0) { + const index = bucket * this.k + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + if (this.nodeArray[index] != null) { + --this.size + return this.nodeArray.splice(index, 1)[0].data + } + --bucket + } + } if (this.size > 0) { --this.size } @@ -102,9 +119,35 @@ export class PriorityQueue { } /** - * Increments the size of the deque. + * Returns an iterator for the priority queue. + * + * @returns An iterator for the priority queue. + * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols + */ + [Symbol.iterator] (): Iterator { + let i = 0 + return { + next: () => { + if (i >= this.nodeArray.length) { + return { + value: undefined, + done: true + } + } + const value = this.nodeArray[i].data + i++ + return { + value, + done: false + } + } + } + } + + /** + * Increments the size of the priority queue. * - * @returns The new size of the deque. + * @returns The new size of the priority queue. */ private incrementSize (): number { ++this.size