有没有人已经在 JavaScript 中实现了循环缓冲区?如果没有指针,你会怎么做?
最佳答案
奇怪的巧合,我今天早些时候刚写了一个!我不知道您的具体要求是什么,但这可能有用。
它提供了一个类似于无限长度数组的接口(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/