refactor: refine biome.js configuration
[poolifier.git] / src / circular-buffer.ts
CommitLineData
f12182ad 1/**
db89e3bc 2 * Default buffer size.
f12182ad
JB
3 */
4export const defaultBufferSize = 2048
5
6/**
0cd1f28c 7 * Circular buffer designed for positive numbers.
db89e3bc 8 * @internal
f12182ad 9 */
0cd1f28c 10export class CircularBuffer {
cf42a4cf 11 private readIdx: number
f12182ad 12 private writeIdx: number
fcfc3353 13 private readonly items: Float32Array
f12182ad 14 private readonly maxArrayIdx: number
cf42a4cf 15 public size: number
f12182ad
JB
16
17 /**
db89e3bc
JB
18 * @param size - Buffer size. @defaultValue defaultBufferSize
19 * @returns CircularBuffer.
f12182ad
JB
20 */
21 constructor (size: number = defaultBufferSize) {
22 this.checkSize(size)
23 this.readIdx = 0
24 this.writeIdx = 0
25 this.maxArrayIdx = size - 1
cf42a4cf 26 this.size = 0
0cd1f28c 27 this.items = new Float32Array(size).fill(-1)
f12182ad
JB
28 }
29
cf42a4cf
JB
30 /**
31 * Checks whether the buffer is empty.
cf42a4cf
JB
32 * @returns Whether the buffer is empty.
33 */
34 public empty (): boolean {
35 return this.size === 0
36 }
37
38 /**
39 * Checks whether the buffer is full.
cf42a4cf
JB
40 * @returns Whether the buffer is full.
41 */
42 public full (): boolean {
43 return this.size === this.items.length
44 }
45
f12182ad 46 /**
0cd1f28c 47 * Puts number into buffer.
0cd1f28c 48 * @param number - Number to put into buffer.
f12182ad 49 */
0cd1f28c
JB
50 public put (number: number): void {
51 this.items[this.writeIdx] = number
f12182ad 52 this.writeIdx = this.writeIdx === this.maxArrayIdx ? 0 : this.writeIdx + 1
cf42a4cf
JB
53 if (this.size < this.items.length) {
54 ++this.size
55 }
56 }
57
58 /**
0cd1f28c 59 * Gets number from buffer.
0cd1f28c 60 * @returns Number from buffer.
cf42a4cf 61 */
0cd1f28c 62 public get (): number | undefined {
f8d5d8fd
JB
63 const number = this.items[this.readIdx]
64 if (number === -1) {
cf42a4cf
JB
65 return
66 }
0cd1f28c 67 this.items[this.readIdx] = -1
cf42a4cf
JB
68 this.readIdx = this.readIdx === this.maxArrayIdx ? 0 : this.readIdx + 1
69 --this.size
f8d5d8fd 70 return number
f12182ad
JB
71 }
72
73 /**
0cd1f28c 74 * Returns buffer as numbers' array.
0cd1f28c 75 * @returns Numbers' array.
f12182ad 76 */
0cd1f28c
JB
77 public toArray (): number[] {
78 return Array.from(this.items.filter(item => item !== -1))
f12182ad
JB
79 }
80
fcfc3353
JB
81 /**
82 * Checks the buffer size.
fcfc3353
JB
83 * @param size - Buffer size.
84 */
f12182ad
JB
85 private checkSize (size: number): void {
86 if (!Number.isSafeInteger(size)) {
87 throw new TypeError(
6e5d7052 88 `Invalid circular buffer size: '${size.toString()}' is not an integer`
f12182ad
JB
89 )
90 }
91 if (size < 0) {
6e5d7052
JB
92 throw new RangeError(
93 `Invalid circular buffer size: ${size.toString()} < 0`
94 )
f12182ad
JB
95 }
96 }
97}