js实现环形
实现环形数组的基本操作
环形数组(Circular Buffer)是一种固定大小的数据结构,遵循先进先出(FIFO)原则,当数组填满时,新数据会覆盖最旧的数据。以下是JavaScript实现环形数组的关键方法:

class CircularBuffer {
constructor(capacity) {
this.buffer = new Array(capacity);
this.capacity = capacity;
this.head = 0; // 写入指针
this.tail = 0; // 读取指针
this.size = 0; // 当前元素数量
}
// 添加元素到环形数组
enqueue(item) {
this.buffer[this.head] = item;
this.head = (this.head + 1) % this.capacity;
if (this.size === this.capacity) {
this.tail = (this.tail + 1) % this.capacity;
} else {
this.size++;
}
}
// 从环形数组移除元素
dequeue() {
if (this.size === 0) return undefined;
const item = this.buffer[this.tail];
this.tail = (this.tail + 1) % this.capacity;
this.size--;
return item;
}
// 查看下一个将被移除的元素
peek() {
return this.size === 0 ? undefined : this.buffer[this.tail];
}
// 清空环形数组
clear() {
this.head = 0;
this.tail = 0;
this.size = 0;
}
}
环形数组的应用场景
环形数组特别适合以下场景:

- 数据流处理(如音频/视频缓冲)
- 固定大小的历史记录存储
- 滑动窗口算法实现
- 高性能队列需求(避免数组元素移动)
环形数组的变体实现
如果需要线程安全版本或支持动态扩容,可以扩展基础实现:
class DynamicCircularBuffer {
constructor(initialCapacity = 8) {
this.buffer = new Array(initialCapacity);
this.capacity = initialCapacity;
this.head = 0;
this.tail = 0;
this.size = 0;
}
// 动态扩容版本
enqueue(item) {
if (this.size === this.capacity) {
this.resize(this.capacity * 2);
}
this.buffer[this.head] = item;
this.head = (this.head + 1) % this.capacity;
this.size++;
}
resize(newCapacity) {
const newBuffer = new Array(newCapacity);
for (let i = 0; i < this.size; i++) {
newBuffer[i] = this.buffer[(this.tail + i) % this.capacity];
}
this.buffer = newBuffer;
this.capacity = newCapacity;
this.tail = 0;
this.head = this.size;
}
}
性能优化建议
- 使用TypedArray(如Uint8Array)处理二进制数据
- 批量操作时考虑缓存局部性
- 对于高频操作场景,避免动态扩容
- 使用位运算代替模运算(当容量为2的幂时)






