1 import { defaultQueueSize
, type FixedQueueNode
, type IFixedQueue
} from
'./utility-types.js'
4 * Fixed priority queue.
5 * @typeParam T - Type of fixed priority queue data.
8 export class FixedPriorityQueue
<T
> implements IFixedQueue
<T
> {
11 public readonly capacity
: number
15 public nodeArray
: FixedQueueNode
<T
>[]
18 * Constructs a fixed priority queue.
19 * @param size - Fixed priority queue size. @defaultValue defaultQueueSize
20 * @returns FixedPriorityQueue.
22 constructor (size
: number = defaultQueueSize
) {
25 this.nodeArray
= new Array<FixedQueueNode
<T
>>(this.capacity
)
30 public empty (): boolean {
31 return this.size
=== 0
35 public full (): boolean {
36 return this.size
=== this.capacity
40 public enqueue (data
: T
, priority
?: number): number {
42 throw new Error('Priority queue is full')
44 priority
= priority
?? 0
46 let index
= this.start
47 for (let i
= 0; i
< this.size
; i
++) {
48 if (this.nodeArray
[index
].priority
> priority
) {
49 this.nodeArray
.splice(index
, 0, { data
, priority
})
50 this.nodeArray
.length
= this.capacity
55 if (index
=== this.capacity
) {
60 let index
= this.start
+ this.size
61 if (index
>= this.capacity
) {
62 index
-= this.capacity
64 this.nodeArray
[index
] = { data
, priority
}
70 public get (index
: number): T
| undefined {
71 if (this.empty() || index
>= this.size
) {
75 if (index
>= this.capacity
) {
76 index
-= this.capacity
78 return this.nodeArray
[index
].data
82 public dequeue (): T
| undefined {
86 const index
= this.start
89 if (this.start
=== this.capacity
) {
92 return this.nodeArray
[index
].data
96 public clear (): void {
102 public [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.capacity
) {
128 * Checks the fixed queue size.
129 * @param size - Queue size.
131 private checkSize (size
: number): void {
132 if (!Number.isSafeInteger(size
)) {
134 `Invalid fixed priority queue size: '${size.toString()}' is not an integer`
138 throw new RangeError(
139 `Invalid fixed priority queue size: ${size.toString()} < 0`