refactor: factor out fixed queue common code in an abstract class
[poolifier.git] / src / fixed-queue.ts
1 import { AbstractFixedQueue } from './abstract-fixed-queue.js'
2 import type { IFixedQueue } from './utility-types.js'
3
4 /**
5 * Fixed queue.
6 * @typeParam T - Type of fixed queue data.
7 * @internal
8 */
9 export class FixedQueue<T>
10 extends AbstractFixedQueue<T>
11 implements IFixedQueue<T> {
12 /** @inheritdoc */
13 public enqueue (data: T, priority?: number): number {
14 if (this.full()) {
15 throw new Error('Fixed queue is full')
16 }
17 let index = this.start + this.size
18 if (index >= this.capacity) {
19 index -= this.capacity
20 }
21 this.nodeArray[index] = { data, priority: priority ?? 0 }
22 return ++this.size
23 }
24
25 /** @inheritdoc */
26 public get (index: number): T | undefined {
27 if (this.empty() || index >= this.size) {
28 return undefined
29 }
30 index += this.start
31 if (index >= this.capacity) {
32 index -= this.capacity
33 }
34 return this.nodeArray[index].data
35 }
36 }