|
| 1 | +function PriorityQueue() { |
| 2 | + |
| 3 | + this.items = []; |
| 4 | + |
| 5 | + function QueueElement (element, priority){ |
| 6 | + this.element = element; |
| 7 | + this.priority = priority; |
| 8 | + } |
| 9 | + |
| 10 | + this.enqueue = function(element, priority){ |
| 11 | + var queueElement = new QueueElement(element, priority); |
| 12 | + |
| 13 | + if (this.isEmpty()){ |
| 14 | + this.items.push(queueElement); |
| 15 | + } else { |
| 16 | + for (var i=0; i<this.items.length; i++){ |
| 17 | + if (queueElement.priority < this.items[i].priority){ |
| 18 | + this.items.splice(i,0,queueElement); |
| 19 | + break; |
| 20 | + } |
| 21 | + } |
| 22 | + } |
| 23 | + }; |
| 24 | + |
| 25 | + this.dequeue = function(){ |
| 26 | + return this.items.shift(); |
| 27 | + }; |
| 28 | + |
| 29 | + this.front = function(){ |
| 30 | + return this.items[0]; |
| 31 | + }; |
| 32 | + |
| 33 | + this.isEmpty = function(){ |
| 34 | + return this.items.length == 0; |
| 35 | + }; |
| 36 | + |
| 37 | + this.size = function(){ |
| 38 | + return this.items.length; |
| 39 | + }; |
| 40 | + |
| 41 | + this.print = function(){ |
| 42 | + for (var i=0; i<this.items.length; i++){ |
| 43 | + console.log(this.items[i].element + ' - ' + this.items[i].priority); |
| 44 | + } |
| 45 | + }; |
| 46 | +} |
| 47 | + |
| 48 | +var priorityQueue = new PriorityQueue(); |
| 49 | +priorityQueue.enqueue("John", 2); |
| 50 | +priorityQueue.enqueue("Jack", 1); |
| 51 | +priorityQueue.enqueue("Camila", 1); |
| 52 | +priorityQueue.print(); |
| 53 | + |
0 commit comments