javascript - JavaScript 中的循环缓冲区

标签 javascript data-structures circular-buffer

有没有人已经在 J​​avaScript 中实现了循环缓冲区?如果没有指针,你会怎么做?

最佳答案

奇怪的巧合,我今天早些时候刚写了一个!我不知道您的具体要求是什么,但这可能有用。

它提供了一个类似于无限长度数组的接口(interface),但“忘记”了旧项目:

// Circular buffer storage. Externally-apparent 'length' increases indefinitely
// while any items with indexes below length-n will be forgotten (undefined
// will be returned if you try to get them, trying to set is an exception).
// n represents the initial length of the array, not a maximum
function CircularBuffer(n) {
    this._array= new Array(n);
    this.length= 0;
}
CircularBuffer.prototype.toString= function() {
    return '[object CircularBuffer('+this._array.length+') length '+this.length+']';
};
CircularBuffer.prototype.get= function(i) {
    if (i<0 || i<this.length-this._array.length)
        return undefined;
    return this._array[i%this._array.length];
};
CircularBuffer.prototype.set= function(i, v) {
    if (i<0 || i<this.length-this._array.length)
        throw CircularBuffer.IndexError;
    while (i>this.length) {
        this._array[this.length%this._array.length]= undefined;
        this.length++;
    }
    this._array[i%this._array.length]= v;
    if (i==this.length)
        this.length++;
};
CircularBuffer.IndexError= {};

关于javascript - JavaScript 中的循环缓冲区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1583123/

相关文章:

javascript - 选择框上的 Angularjs ngKeyup 不起作用

c++ - 返回索引并在 C++ 中存储字符串计数的数据结构

javascript - Highcharts 在 x 轴上多次显示额外标签

javascript - 格式化获取请求的路由

c++ - 使用 map 容器的字母频率

android - Android SDK 的 CircularArray 线程安全吗?

c - 如何优化简单的循环/旋转缓冲区/FIFO 处理以提高性能

c++ - Boost Circular Buffer,如何让它在填充时调用一些函数?

javascript - 事件冒泡的优点与事件捕获的优点

java - 重新排列数组使得 arr[i] = i