4 export const defaultQueueSize
= 2048
9 * @typeParam T - Type of priority queue node data.
12 export interface PriorityQueueNode
<T
> {
18 * Fixed priority queue.
20 * @typeParam T - Type of fixed priority queue data.
23 export class FixedPriorityQueue
<T
> {
24 private start
!: number
25 private readonly nodeArray
: Array<PriorityQueueNode
<T
>>
27 public maxSize
!: number
29 constructor (size
: number = defaultQueueSize
) {
31 this.nodeArray
= new Array<PriorityQueueNode
<T
>>(size
)
35 public empty (): boolean {
36 return this.size
=== 0
39 public full (): boolean {
40 return this.size
=== this.nodeArray
.length
43 public enqueue (data
: T
, priority
?: number): number {
45 throw new Error('Priority queue is full')
47 priority
= priority
?? 0
48 const nodeArrayLength
= this.nodeArray
.length
49 let index
= this.start
51 for (let i
= 0; i
< this.size
; i
++) {
52 if (this.nodeArray
[index
]?.priority
> priority
) {
53 this.nodeArray
.splice(index
, 0, { data
, priority
})
58 if (index
=== nodeArrayLength
) {
62 this.nodeArray
.length
!== nodeArrayLength
&&
63 (this.nodeArray
.length
= nodeArrayLength
)
65 let index
= this.start
+ this.size
66 if (index
>= nodeArrayLength
) {
67 index
-= nodeArrayLength
69 this.nodeArray
[index
] = { data
, priority
}
71 return this.incrementSize()
74 public dequeue (): T
| undefined {
78 const index
= this.start
81 if (this.start
=== this.nodeArray
.length
) {
84 return this.nodeArray
[index
].data
88 * Clears the fixed priority queue.
90 public clear (): void {
97 * Returns an iterator for the fixed priority queue.
99 * @returns An iterator for the fixed priority queue.
100 * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols
102 [Symbol
.iterator
] (): Iterator
<T
> {
103 let index
= this.start
107 if (i
>= this.size
) {
113 const value
= this.nodeArray
[index
].data
116 if (index
=== this.nodeArray
.length
) {
128 * Increments the size of the fixed priority queue.
130 * @returns The new size of the fixed priority queue.
132 private incrementSize (): number {
134 if (this.size
> this.maxSize
) {
135 this.maxSize
= this.size
140 private checkSize (size
: number): void {
141 if (!Number.isSafeInteger(size
)) {
143 `Invalid fixed priority queue size: '${size}' is not an integer`
147 throw new RangeError(`Invalid fixed priority queue size: ${size} < 0`)