Skip to content

Instantly share code, notes, and snippets.

@bryanberger
Last active December 13, 2015 22:08
Show Gist options
  • Save bryanberger/4982254 to your computer and use it in GitHub Desktop.
Save bryanberger/4982254 to your computer and use it in GitHub Desktop.
Simple Javascript Circular Buffer
/** one way of doing it **/
var CircularBuffer = exports.CircularBuffer = function(size) {
this.pos = 0
this._buf = []
this.size = size
}
CircularBuffer.prototype.get = function(i) {
if (i == undefined) i = 0;
if (i >= this.size) return undefined;
if (i >= this._buf.length) return undefined;
return this._buf[(this.pos - i - 1) % this.size]
}
CircularBuffer.prototype.push = function(o) {
this._buf[this.pos % this.size] = o
this.pos++
return o
}
/** another way of doing it **/
var CircularBuffer = function(size) {
this._buf = new Array(size); //= new Array(size);
this.pos = 0;
}
CircularBuffer.prototype.get = function(i) {
if (i == undefined) i = 0;
if (i > this._buf.length) return null;
return this._buf[i % this._buf.length];
};
CircularBuffer.prototype.push= function(o) {
this._buf[this.pos % this._buf.length] = o;
this.pos++;
};
CircularBuffer.prototype.toString = function() {
return '[object CircularBuffer('+this._buf.length+') length '+this.pos+']';
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment