5 } from
'./utility-types.js'
8 * Fixed priority queue.
9 * @typeParam T - Type of fixed priority queue data.
12 export class FixedPriorityQueue
<T
> implements IFixedQueue
<T
> {
13 private start
!: number
15 public readonly capacity
: number
19 public nodeArray
: FixedQueueNode
<T
>[]
22 * Constructs a fixed priority queue.
23 * @param size - Fixed priority queue size. @defaultValue defaultQueueSize
24 * @returns FixedPriorityQueue.
26 constructor (size
: number = defaultQueueSize
) {
29 this.nodeArray
= new Array<FixedQueueNode
<T
>>(this.capacity
)
34 public empty (): boolean {
35 return this.size
=== 0
39 public full (): boolean {
40 return this.size
=== this.capacity
44 public enqueue (data
: T
, priority
?: number): number {
46 throw new Error('Fixed priority queue is full')
48 priority
= priority
?? 0
50 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
})
54 this.nodeArray
.length
= this.capacity
59 if (index
=== this.capacity
) {
64 let index
= this.start
+ this.size
65 if (index
>= this.capacity
) {
66 index
-= this.capacity
68 this.nodeArray
[index
] = { data
, priority
}
74 public get (index
: number): T
| undefined {
75 if (this.empty() || index
>= this.size
) {
79 if (index
>= this.capacity
) {
80 index
-= this.capacity
82 return this.nodeArray
[index
].data
86 public dequeue (): T
| undefined {
90 const index
= this.start
93 if (this.start
=== this.capacity
) {
96 return this.nodeArray
[index
].data
100 public clear (): void {
106 public [Symbol
.iterator
] (): Iterator
<T
> {
107 let index
= this.start
111 if (i
>= this.size
) {
117 const value
= this.nodeArray
[index
].data
120 if (index
=== this.capacity
) {
132 * Checks the fixed queue size.
133 * @param size - Queue size.
135 private checkSize (size
: number): void {
136 if (!Number.isSafeInteger(size
)) {
138 `Invalid fixed priority queue size: '${size.toString()}' is not an integer`
142 throw new RangeError(
143 `Invalid fixed priority queue size: ${size.toString()} < 0`