June 21, 2011

Queue in JavaScript


Queue is an ADT (Abstract Data Type), which has the basic operations like enque/dequeue. Enqueue operation will insert an item to the queue. Dequeue will return the first inserted element. The constructor will accept max size for the queue. On overflow both enqueue & dequeue will return false.


function Queue(max){
  this.max = max;
}
Queue.prototype = (function(){
   var queue = [];
   return {
      enqueue: function(item){
         if(queue.length == this.max){
            return false;
         }
         queue.push(item);
      },
      dequeue: function(){
         if(queue.length == 0){
            return false;
         }
         return queue.shift();
      },
      isEmpty:function(){
         return queue.length == 0;
      }
   }
}
)();

No comments:

Post a Comment