Skip to content

Instantly share code, notes, and snippets.

@blowery
Created October 7, 2009 14:35
Show Gist options
  • Save blowery/204087 to your computer and use it in GitHub Desktop.
Save blowery/204087 to your computer and use it in GitHub Desktop.
// A RingBufffer
function RingBuffer(sz) {
this._max = sz;
this._buffer = new Array(sz);
this._head = -1;
}
RingBuffer.prototype = {
push: function(el){
// summary: Push a new element into the ring buffer.
// May discard the oldest existing element.
var h = this._head + 1;
if(h === this._max) h = 0; // wrap to the beginning
this._buffer[h] = el;
this._head = h;
return this;
},
pop: function(){
// summary: Pull the most recently pushed element out of
// the buffer.
var el = this._buffer[this._head];
if(el === undefined) {
return undefined;
}
var h = this._head - 1;
if(h === -1 && this._buffer[this._max-1] !== undefined) {
h = this._max-1;
}
this._buffer[this._head] = undefined;
this._head = h;
return el;
},
_visit: function(fn){
var l=0,h=this._head;
while(this._buffer[h] !== undefined && l !== this._max) {
if(fn) fn(this._buffer[h], l);
l++; h--;
if(h === -1 && this._buffer[this._max - 1] !== undefined) {
h = this._max - 1;
}
}
return l;
},
length: function(){
return this._visit();
},
toArray: function(){
var ar = [];
this._visit(function(el) { ar.push(el); } );
return ar;
},
toString: function(){
var body = this.length() === 0 ? "" : "[ " + this.toArray().join(", ") + " ]";
return "[RingBuffer " + body + "]";
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment