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
20 * @param size - Buffer size. @defaultValue defaultBufferSize
21 * @returns CircularBuffer.
23 constructor (size
: number = defaultBufferSize
) {
27 this.maxArrayIdx
= size
- 1
29 this.items
= new Array<T
| undefined>(size
)
33 * Checks whether the buffer is empty.
35 * @returns Whether the buffer is empty.
37 public empty (): boolean {
38 return this.size
=== 0
42 * Checks whether the buffer is full.
44 * @returns Whether the buffer is full.
46 public full (): boolean {
47 return this.size
=== this.items
.length
51 * Puts data into buffer.
53 * @param data - Data to put into buffer.
55 public put (data
: T
): void {
56 this.items
[this.writeIdx
] = data
57 this.writeIdx
= this.writeIdx
=== this.maxArrayIdx
? 0 : this.writeIdx
+ 1
58 if (this.size
< this.items
.length
) {
64 * Gets data from buffer.
66 * @returns Data from buffer.
68 public get (): T
| undefined {
69 const data
= this.items
[this.readIdx
]
73 this.items
[this.readIdx
] = undefined
74 this.readIdx
= this.readIdx
=== this.maxArrayIdx
? 0 : this.readIdx
+ 1
80 * Returns buffer as array.
82 * @returns Array of buffer data.
84 public toArray (): T
[] {
85 return this.items
.filter(item
=> item
!= null) as T
[]
88 private checkSize (size
: number): void {
89 if (!Number.isSafeInteger(size
)) {
91 `Invalid circular buffer size: ${size} is not an integer`
95 throw new RangeError(`Invalid circular buffer size: ${size} < 0`)