June 21, 2011

Stack in JavaScript

Stack is an ADT (Abstract Data Type), which has basic operations like push and pop. Push will insert a new item to the stack. If the stack is empty then it'll initialize it. Pop operation will remove the last inserted item and returns it. The simple implementation of stack in JavaScript is here (Using JavaScript array which already has push & pop implementation).

function Stack(max){
   this.max = max;
}
Stack.prototype = (function(){
   var stack = [];
   return {
      push: function(item){
         if(stack.length == this.max){
            //Stack overflow.
            return false;
         }
         stack.push(item);
      },
      pop: function(){
         if(stack.length == 0){
             return false;//Stack is empty.
         }
         return stack.pop();
      },
      isEmpty:function(){
         return stack.length == 0;
      }
   }
}
)();

No comments:

Post a Comment