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