Skip to content

Instantly share code, notes, and snippets.

@luisfarzati
Created March 6, 2014 02:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save luisfarzati/9380972 to your computer and use it in GitHub Desktop.
Save luisfarzati/9380972 to your computer and use it in GitHub Desktop.
Simple/Circular buffers for JavaScript
function BufferOverflowError(message) {
this.message = message;
}
BufferOverflowError.prototype = new Error();
BufferOverflowError.prototype.constructor = BufferOverflowError;
function Buffer(size) {
this.__size = size || Infinity;
this.__buffer = [];
}
Buffer.prototype.add = function (item) {
if (this.__buffer.length + 1 > this.__size) {
throw new BufferOverflowError('Buffer has exceeded its configured size of ' + this.__size + ' elements');
}
return this.__buffer.push(item);
};
Buffer.prototype.flush = function (handlerFn) {
this.__buffer.forEach(handlerFn);
this.__buffer.length = 0;
};
function CircularBuffer(size) {
if (angular.isUndefined(size)) {
throw new Error('Fixed-size buffer requires a size');
}
Buffer.call(this, size);
this.__index = -1;
}
CircularBuffer.prototype.add = function (item) {
this.__buffer[++this.__index % this.__size] = item;
};
CircularBuffer.prototype.flush = function (handlerFn) {
for (var i = this.__index + 1; i <= this.__size + this.__index; i++) {
var item = this.__buffer[i % this.__size];
if (angular.isDefined(item)) {
handlerFn(item);
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment