Pages

Thursday, December 30, 2010

Queue In Javascript

/**
 * A Queue ADT. This ADT provide functionality for FIFO 
 * data structure.
 *
 * @author  : irfanudin ridho
 * @email   : irfan.ub@gmail.com
 * @date    : December 31, 2010
 * @version : 1.0
 */

/**
 * A constructor service.
 */
function Queue(){
    this.data = new Array();
}

/**
 * method to insert an element to the Queue
 *
 * @param item string, number, boolean element to be inserted.
 */
Queue.prototype.push = function(item){
    var len = this.data.length;
    var newData = new Array();
    newData[0] = item;
    for(i=0;i<len;i++){
        newData[i+1]=this.data[i];
    }
    this.data = newData;
};

/**
 * A method to remove the first item inserted.
 *
 * @return first element of the Queue.
 */
Queue.prototype.pop = function(){
    var len = this.data.length;
    var first = this.data[len-1];
    var newData = new Array();
    for(i=1;i<len;i++){
        newData[i-1]=this.data[i];
    }
    this.data = newData;
    return first;
};

/**
 * A method to get how many elements in the Queue
 *
 * @return number number of elements.
 */
Queue.prototype.size = function(){
    return this.data.length;
};

/**
 * A method to represent this queue as an array data structure.
 *
 * @return array of data
 */
Queue.prototype.toArray = function(){
    return this.data;
}

No comments:

Post a Comment