queue

佇列

by Chris_Walter

JavaScript

class QueueItems{
  constructor(priority, element){
	  this.priority = priority;
		this.element = element;
	}
}

class PriorityQueue{
  constructor(){
	  this.cache = [];
	}
	isEmpty(){
	  return this.cache.length === 0;
	}
	enqueue(priority, element){
	  let queueItems = new QueueItems(priority, element);
	  if(this.isEmpty()){
		  this.cache.push(queueItems);
		} else{
		    let added = false;
				/*如果當前的priority值小於cache裡的priority使用splice()方法插入=>當執行時i=0; i<2;i++
          i=0時,cache = [{element: 'Alan", priority:2},{element: 'Sandy", priority:3}]
          i=1時,cache = [{element: 'Alan", priority:2},{element: 'Sandy", priority:3}.{element: 'Tony", priority:2}]
      */
		    for(let i=0; i<this.cache.length; i++){
		      if(queueItems.priority < this.cache[i].priority){
			    this.cache.splice(i, 0, queueItems);
					added = true;
				  break;
			  }
		  }
			//如果當前的priority值大於cache裡面的priority直接新增到佇列末尾
			if(!added){
			  this.cache.push(queueItems);
			}
		}
		return this.cache;
	}
	dequeue(){
	  return this.cache.shift();
	}
	front(){
	  return this.cache[0];
	}
	size(){
	  return this.cache.length;
	}
}

let priorityQueueInstance = new PriorityQueue();
console.log(priorityQueueInstance.enqueue(2, 'Alan'));
console.log(priorityQueueInstance.enqueue(3, 'Sandy'));
console.log(priorityQueueInstance.enqueue(2, 'Tony'));