bebraw
10/19/2010 - 6:34 AM

Simple Implementation of a Queue in JavaScript. Note the handy index based access.

Simple Implementation of a Queue in JavaScript. Note the handy index based access.

function Queue(maxLength) {
    this.init(maxLength);
}
Queue.prototype = {
    init: function (maxLength) {
        this.maxLength =  maxLength;
        this.length = 0;
    },
    push: function (item) {
        if(this.length == this.maxLength) {
            for(var i = 0; i < this.maxLength - 1; i++) {
                this[i] = this[i+1];
            }
            this[this.length - 1] = item;
        }
        else {
            this[this.length] = item;
            this.length++;
        }
    }
}

// Usage (not tested)
var q = new Queue(3);
q.push(3);
q[0]; // should ret 3. [1] and [2] should be undefined still
q.push(2);
q[0]; // returns 2 (q[1] is 3)
q.push(4)
q.push(5)
// content [5, 4, 2]