Pages

Thursday, December 30, 2010

Stack In Javascript

/**
 * An ADT of Stack. This is an implementation of LIFO 
 * data structure.
 *
 * @author  : irfanudin ridho
 * @email   : irfan.ub@gmail.com
 * @date    : December 31, 2010
 * @version : 1.0
 */

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

/**
 * A method to insert an element to the top position.
 *
 * @param item string, number or boolean value to be inserted
 */
Stack.prototype.push = function(item){
    var len = this.data.length;
    this.data[len]=item;
};

/**
 * A method to get the top position from the stack. As well as
 * to remove it.
 *
 * @return the value of the top position.
 */
Stack.prototype.pop = function(){
    var len = this.data.length;
    var last = this.data[len-1];
    var newStack = new Array();
    for(i=0;i<len-1;i++){
        newStack[i]=this.data[i];
    }
    this.data = newStack;
    return last;
};

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

/**
 * A method to convert the stack to be an array representation.
 *
 * @return an array of data.
 */
Stack.prototype.toArray = function(){
     return this.data;
}
         

No comments:

Post a Comment