Last active
December 13, 2015 22:08
-
-
Save bryanberger/4982254 to your computer and use it in GitHub Desktop.
Simple Javascript Circular Buffer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** 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