Created
March 6, 2014 02:17
-
-
Save luisfarzati/9380972 to your computer and use it in GitHub Desktop.
Simple/Circular buffers for JavaScript
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
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