4 export const defaultBufferSize
= 2048
7 * Circular buffer designed for positive numbers.
11 export class CircularBuffer
{
12 private readIdx
: number
13 private writeIdx
: number
14 private readonly items
: Float32Array
15 private readonly maxArrayIdx
: number
19 * @param size - Buffer size. @defaultValue defaultBufferSize
20 * @returns CircularBuffer.
22 constructor (size
: number = defaultBufferSize
) {
26 this.maxArrayIdx
= size
- 1
28 this.items
= new Float32Array(size
).fill(-1)
32 * Checks whether the buffer is empty.
34 * @returns Whether the buffer is empty.
36 public empty (): boolean {
37 return this.size
=== 0
41 * Checks whether the buffer is full.
43 * @returns Whether the buffer is full.
45 public full (): boolean {
46 return this.size
=== this.items
.length
50 * Puts number into buffer.
52 * @param number - Number to put into buffer.
54 public put (number: number): void {
55 this.items
[this.writeIdx
] = number
56 this.writeIdx
= this.writeIdx
=== this.maxArrayIdx
? 0 : this.writeIdx
+ 1
57 if (this.size
< this.items
.length
) {
63 * Gets number from buffer.
65 * @returns Number from buffer.
67 public get (): number | undefined {
68 const number = this.items
[this.readIdx
]
72 this.items
[this.readIdx
] = -1
73 this.readIdx
= this.readIdx
=== this.maxArrayIdx
? 0 : this.readIdx
+ 1
79 * Returns buffer as numbers' array.
81 * @returns Numbers' array.
83 public toArray (): number[] {
84 return Array.from(this.items
.filter(item
=> item
!== -1))
88 * Checks the buffer size.
90 * @param size - Buffer size.
92 private checkSize (size
: number): void {
93 if (!Number.isSafeInteger(size
)) {
95 `Invalid circular buffer size: '${size}' is not an integer`
99 throw new RangeError(`Invalid circular buffer size: ${size} < 0`)