4 export const defaultBufferSize
= 2048
9 * @typeParam T - Type of buffer data.
12 export class CircularBuffer
<T
> {
13 private readIdx
: number
14 private writeIdx
: number
15 private items
: Array<T
| undefined>
16 private readonly maxArrayIdx
: number
17 /* Buffer number of elements */
21 * @param size - Buffer size. @defaultValue defaultBufferSize
22 * @returns CircularBuffer.
24 constructor (size
: number = defaultBufferSize
) {
28 this.maxArrayIdx
= size
- 1
30 this.items
= new Array<T
| undefined>(size
)
34 * Checks whether the buffer is empty.
36 * @returns Whether the buffer is empty.
38 public empty (): boolean {
39 return this.size
=== 0
43 * Checks whether the buffer is full.
45 * @returns Whether the buffer is full.
47 public full (): boolean {
48 return this.size
=== this.items
.length
52 * Puts data into buffer.
54 * @param data - Data to put into buffer.
56 public put (data
: T
): void {
57 this.items
[this.writeIdx
] = data
58 this.writeIdx
= this.writeIdx
=== this.maxArrayIdx
? 0 : this.writeIdx
+ 1
59 if (this.size
< this.items
.length
) {
65 * Gets data from buffer.
67 * @returns Data from buffer.
69 public get (): T
| undefined {
70 const data
= this.items
[this.readIdx
]
74 this.items
[this.readIdx
] = undefined
75 this.readIdx
= this.readIdx
=== this.maxArrayIdx
? 0 : this.readIdx
+ 1
81 * Returns buffer as array.
83 * @returns Array of buffer data.
85 public toArray (): T
[] {
86 return this.items
.filter(item
=> item
!= null) as T
[]
89 private checkSize (size
: number): void {
90 if (!Number.isSafeInteger(size
)) {
92 `Invalid circular buffer size: ${size} is not an integer`
96 throw new RangeError(`Invalid circular buffer size: ${size} < 0`)