Skip to content

Commit 10eb39a

Browse files
committed
RingBuffer example
1 parent 5a9f832 commit 10eb39a

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

JavaScript/3-ring.js

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
'use strict';
2+
3+
class RingBuffer {
4+
constructor(size) {
5+
this.size = size;
6+
this.buffer = Buffer.alloc(size);
7+
this.offset = 0;
8+
}
9+
10+
write(data) {
11+
const { size, offset } = this;
12+
const { length } = data;
13+
const available = size - offset;
14+
const end = Math.min(offset + length, size + 1);
15+
const rest = available - length;
16+
let position = 0;
17+
for (let i = offset; i < end; i++) {
18+
this.buffer[i] = data.charCodeAt(position++);
19+
}
20+
this.offset += position;
21+
if (this.offset > size) this.offset = 0;
22+
if (rest < 0) this.write(data.slice(rest));
23+
}
24+
}
25+
26+
// Usage
27+
28+
const ring = new RingBuffer(10);
29+
ring.write('1');
30+
console.log(ring.buffer.toString('utf8'));
31+
ring.write('23');
32+
console.log(ring.buffer.toString('utf8'));
33+
ring.write('4567890A');
34+
console.log(ring.buffer.toString('utf8'));
35+
ring.buffer.write('B');
36+
console.log(ring.buffer.toString('utf8'));

0 commit comments

Comments
 (0)