803af1294f83eb0f094cd6d2ab40e52353408ed7
4 export const defaultBufferSize
= 2048
7 * Circular buffer designed for positive numbers.
10 export class CircularBuffer
{
11 private readonly items
: Float32Array
12 private readonly maxArrayIdx
: number
13 private readIdx
: number
14 private writeIdx
: number
18 * @param size - Buffer size. @defaultValue defaultBufferSize
19 * @returns CircularBuffer.
21 constructor (size
: number = defaultBufferSize
) {
25 this.maxArrayIdx
= size
- 1
27 this.items
= new Float32Array(size
).fill(-1)
31 * Checks the buffer size.
32 * @param size - Buffer size.
34 private checkSize (size
: number): void {
35 if (!Number.isSafeInteger(size
)) {
37 `Invalid circular buffer size: '${size.toString()}' is not an integer`
42 `Invalid circular buffer size: ${size.toString()} < 0`
48 * Checks whether the buffer is empty.
49 * @returns Whether the buffer is empty.
51 public empty (): boolean {
52 return this.size
=== 0
56 * Checks whether the buffer is full.
57 * @returns Whether the buffer is full.
59 public full (): boolean {
60 return this.size
=== this.items
.length
64 * 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 * Puts number into buffer.
80 * @param number - Number to put into buffer.
82 public put (number: number): void {
83 this.items
[this.writeIdx
] = number
84 this.writeIdx
= this.writeIdx
=== this.maxArrayIdx
? 0 : this.writeIdx
+ 1
85 if (this.size
< this.items
.length
) {
91 * Returns buffer as numbers' array.
92 * @returns Numbers' array.
94 public toArray (): number[] {
95 return Array.from(this.items
.filter(item
=> item
!== -1))