tvolodimir
1/10/2014 - 8:55 AM

CircleBuffer

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;
        }
    }
};