3 var RingBuffer = function(bufferSize) {
4 this._buffer = new Array(bufferSize);
5 this._bufferSize = bufferSize;
7 this._ringSize = bufferSize;
13 RingBuffer.prototype.push = function(value) {
14 var expandBuffer = false,
17 if (this._ringSize < this._bufferSize) {
18 expandBuffer = (this._tail === 0);
19 } else if (this._ringOffset === this._ringSize) {
21 expandRing = (this._tail === 0);
25 this._tail = this._bufferSize;
26 this._buffer = this._buffer.concat(new Array(this._bufferSize));
27 this._bufferSize = this._buffer.length;
30 this._ringSize = this._bufferSize;
33 this._buffer[this._tail] = value;
35 if (this._tail < this._ringSize) this._ringOffset += 1;
36 this._tail = (this._tail + 1) % this._bufferSize;
39 RingBuffer.prototype.peek = function() {
40 if (this.length === 0) return void 0;
41 return this._buffer[this._head];
44 RingBuffer.prototype.shift = function() {
45 if (this.length === 0) return void 0;
47 var value = this._buffer[this._head];
48 this._buffer[this._head] = void 0;
50 this._ringOffset -= 1;
52 if (this._ringOffset === 0 && this.length > 0) {
53 this._head = this._ringSize;
54 this._ringOffset = this.length;
55 this._ringSize = this._bufferSize;
57 this._head = (this._head + 1) % this._ringSize;
62 module.exports = RingBuffer;