Created
January 14, 2026 09:33
-
-
Save abel-masila/fa7869796833b514cec45277e499bd1b to your computer and use it in GitHub Desktop.
A ring buffer (or circular buffer/queue) in JavaScript is a fixed-size data structure that reuses memory by connecting the last element to the first, operating in a First-In, First-Out (FIFO) manner. It is commonly implemented using a standard JavaScript Array and modulo arithmetic to manage read/write pointers.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class RingBuffer { | |
| constructor(capacity) { | |
| this.capacity = capacity; | |
| this.buffer = new Array(capacity); | |
| this.head = 0; // Read pointer | |
| this.tail = 0; // Write pointer | |
| this.count = 0; // Current number of elements | |
| } | |
| // Add an element to the buffer (overwrites oldest if full) | |
| enqueue(item) { | |
| if (this.isFull()) { | |
| this.head = (this.head + 1) % this.capacity; // Advance head to discard oldest | |
| } else { | |
| this.count++; | |
| } | |
| this.buffer[this.tail] = item; | |
| this.tail = (this.tail + 1) % this.capacity; // Wrap around using modulo | |
| } | |
| // Remove and return the oldest element from the buffer | |
| dequeue() { | |
| if (this.isEmpty()) { | |
| return undefined; // Or throw an error | |
| } | |
| const item = this.buffer[this.head]; | |
| delete this.buffer[this.head]; // Optional: free memory slot | |
| this.head = (this.head + 1) % this.capacity; // Wrap around using modulo | |
| this.count--; | |
| return item; | |
| } | |
| // Peek at the oldest element without removing it | |
| peek() { | |
| if (this.isEmpty()) return undefined; | |
| return this.buffer[this.head]; | |
| } | |
| isEmpty() { | |
| return this.count === 0; | |
| } | |
| isFull() { | |
| return this.count === this.capacity; | |
| } | |
| size() { | |
| return this.count; | |
| } | |
| } | |
| // Example Usage: | |
| const buffer = new RingBuffer(3); | |
| buffer.enqueue('A'); | |
| buffer.enqueue('B'); | |
| buffer.enqueue('C'); | |
| console.log(buffer.dequeue()); // Output: A | |
| buffer.enqueue('D'); // Overwrites 'B' | |
| console.log(buffer.dequeue()); // Output: C | |
| console.log(buffer.dequeue()); // Output: D | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment