Sunday, May 19, 2024
111
rated 0 times [  113] [ 2]  / answers: 1 / hits: 45069  / 15 Years ago, sat, october 17, 2009, 12:00:00

Has anyone already implemented a circular buffer in JavaScript? How would you do that without having pointers?


More From » data-structures

 Answers
6

Strange co-incidence, I just wrote one earlier today! I don't know what exactly your requirements are but this might be of use.



It presents an interface like an Array of unlimited length, but ‘forgets’ old items:



// 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= {};

[#98493] Tuesday, October 13, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
brynn

Total Points: 448
Total Questions: 83
Total Answers: 118

Location: Albania
Member since Sun, Nov 22, 2020
4 Years ago
;