d1d9307804822bd7a243fe51004ee1bb9b08a280
1 // Copyright Jerome Benoit. 2024. All Rights Reserved.
3 import { FixedPriorityQueue
} from
'./fixed-priority-queue.js'
8 export const defaultBucketSize
= 2048
11 * Priority queue node.
13 * @typeParam T - Type of priority queue node data.
16 export interface PriorityQueueNode
<T
> extends FixedPriorityQueue
<T
> {
17 next
?: FixedPriorityQueue
<T
>
23 * @typeParam T - Type of priority queue data.
26 export class PriorityQueue
<T
> {
27 private head
!: PriorityQueueNode
<T
>
28 private tail
!: PriorityQueueNode
<T
>
29 private readonly bucketSize
: number
30 public maxSize
!: number
33 * Constructs a priority queue.
35 * @param bucketSize - Prioritized bucket size. @defaultValue defaultBucketSize
36 * @returns PriorityQueue.
38 public constructor (bucketSize
: number = defaultBucketSize
) {
39 this.bucketSize
= bucketSize
43 /** The size of the priority queue. */
44 public get
size (): number {
45 let node
: PriorityQueueNode
<T
> | undefined = this.tail
47 while (node
!= null) {
55 * Enqueue data into the priority queue.
57 * @param data - Data to enqueue.
58 * @param priority - Priority of the data. Lower values have higher priority.
59 * @returns The new size of the priority queue.
61 public enqueue (data
: T
, priority
?: number): number {
62 if (this.head
.full()) {
63 this.head
= this.head
.next
= new FixedPriorityQueue(this.bucketSize
)
65 this.head
.enqueue(data
, priority
)
66 const size
= this.size
67 if (size
> this.maxSize
) {
74 * Dequeue data from the priority queue.
76 * @param bucket - The prioritized bucket to dequeue from.
77 * @returns The dequeued data or `undefined` if the priority queue is empty.
79 public dequeue (bucket
?: number): T
| undefined {
80 let tail
: PriorityQueueNode
<T
> | undefined = this.tail
83 while (tail
!= null) {
85 if (currentBucket
=== bucket
) {
91 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
92 const data
= tail
!.dequeue()
93 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
94 if (tail
!.empty() && tail
!.next
!= null) {
95 if (tail
=== this.tail
) {
98 let node
: PriorityQueueNode
<T
> | undefined = this.tail
99 while (node
!= null) {
100 if (node
.next
=== tail
) {
101 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
102 node
.next
= tail
!.next
108 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
115 * Clears the priority queue.
117 public clear (): void {
118 this.head
= this.tail
= new FixedPriorityQueue(this.bucketSize
)
123 * Returns an iterator for the priority queue.
125 * @returns An iterator for the priority queue.
126 * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols
128 public [Symbol
.iterator
] (): Iterator
<T
> {
133 if (node
.empty() || (i
>= node
.capacity
&& node
.next
== null)) {
139 const value
= node
.dequeue() as T
141 if (i
=== node
.capacity
&& node
.next
!= null) {