Skip to content

Instantly share code, notes, and snippets.

@tvolodimir
Created January 10, 2014 08:55
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 tvolodimir/8348765 to your computer and use it in GitHub Desktop.
Save tvolodimir/8348765 to your computer and use it in GitHub Desktop.
CircleBuffer
// http://jsperf.com/circle-buffer-vc-array
var CircleBuffer = function (size) {
this._size = size; // max count of data
this._list = [];
this._cursorIndex = 0;
this._startIndex = 0;
this.length = 0; // actual data length
};
CircleBuffer.prototype = {
constructor: CircleBuffer,
push: function (data) {
this.length++;
if (this.length > this._size) {
this.length = this._size;
this._startIndex++;
this._startIndex = this._startIndex % this._size;
}
this._list[this._cursorIndex++] = data;
this._cursorIndex = this._cursorIndex % this._size;
},
shift: function () {
if (this.length > 0) {
var _i = this._startIndex % this._size;
var _v = this._list[_i];
delete this._list[_i];
this._startIndex += 1;
this.length -= 1;
return _v;
}
},
get: function (index) {
if (index > -1 && index < this.length) {
return this._list[(this._startIndex + index) % this._size];
}
},
removeAtBegin: function (count) {
if (count >= this.length) {
this.clear();
return;
}
if (count > 0) {
for (var i = 0; i < count; i++) {
delete this._list[(this._startIndex + i) % this._size];
}
this._startIndex += count;
this.length -= count;
}
},
first: function () {
if (this.length > 0) {
return this._list[this._startIndex % this._size];
}
},
last: function () {
if (this.length > 0) {
return this._list[(this._startIndex + this.length - 1) % this._size];
}
},
clear: function () {
if (this.length > 0) {
this._list.length = 0;
this._cursorIndex = 0;
this._startIndex = 0;
this.length = 0;
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment