es-next-tools
Version:
A comprehensive utility library for JavaScript and TypeScript that provides a wide range of functions for common programming tasks, including mathematical operations, date manipulations, array and object handling, string utilities, and more.
60 lines (59 loc) • 1.61 kB
JavaScript
/**
* Represents a circular buffer data structure.
* @template T The type of elements in the circular buffer.
*/
export class CircularBuffer {
buffer;
head = 0;
tail = 0;
size = 0;
capacity;
/**
* Creates a circular buffer with a specified capacity.
* @param {number} capacity - The maximum number of items the buffer can hold.
*/
constructor(capacity) {
this.capacity = capacity;
this.buffer = new Array(capacity);
}
/**
* Adds an item to the buffer.
* @param {T} item - The item to add.
*/
add(item) {
this.buffer[this.tail] = item;
this.tail = (this.tail + 1) % this.capacity;
if (this.size < this.capacity) {
this.size++;
}
else {
this.head = (this.head + 1) % this.capacity; // Overwrite the oldest item
}
}
/**
* Removes and returns the oldest item from the buffer.
* @returns {T | undefined} The oldest item, or undefined if the buffer is empty.
*/
remove() {
if (this.size === 0)
return undefined;
const item = this.buffer[this.head];
this.head = (this.head + 1) % this.capacity;
this.size--;
return item;
}
/**
* Returns the current size of the buffer.
* @returns {number} The number of items in the buffer.
*/
getSize() {
return this.size;
}
/**
* Checks if the buffer is empty.
* @returns {boolean} True if the buffer is empty, false otherwise.
*/
isEmpty() {
return this.size === 0;
}
}