|
| 1 | +A Priority Queue is a special type of Queue in which items may have additional information which specifies their priority. |
| 2 | +This could be simply represented with an integer. |
| 3 | +Item priority will override placement order in determining the sequence items are dequeued. |
| 4 | +If an item with a higher priority is enqueued after items with lower priority, |
| 5 | +the higher priority item will be dequeued before all the others. |
| 6 | + |
| 7 | +For instance, let’s imagine we have a priority queue with three items: |
| 8 | + |
| 9 | +`[['kitten', 2], ['dog', 2], ['rabbit', 2]]` |
| 10 | + |
| 11 | +Here the second value (an integer) represents item priority. If we enqueue `['human', 1]` with a priority of `1` (assuming lower priorities are given precedence) it would then be the first item to be dequeued. The collection would like this: |
| 12 | + |
| 13 | +`[['human', 1], ['kitten', 2], ['dog', 2], ['rabbit', 2]]`. |
| 14 | + |
| 15 | +We’ve started writing a `PriorityQueue` in the code editor. |
| 16 | +You will need to add an `enqueue` method for adding items with a priority, |
| 17 | +a `dequeue` method for removing items, a `size` method to return the number of items in the queue, |
| 18 | +a `front` method to return the element at the front of the queue, |
| 19 | +and finally an `isEmpty` method that will return true if the queue is empty or false if it is not. |
| 20 | + |
| 21 | +The enqueue should accept items with the format shown above `(['human', 1])` where `1` represents the priority. |
| 22 | +The dequeue should return only the current item, not its priority. |
| 23 | + |
| 24 | +```js |
| 25 | +function PriorityQueue () { |
| 26 | + this.collection = []; |
| 27 | + this.printCollection = function() { |
| 28 | + console.log(this.collection); |
| 29 | + }; |
| 30 | + this.enqueue = function(priorityItem) { |
| 31 | + let inserted = false; |
| 32 | + for (let i = 0; i < this.collection.length; i++) { |
| 33 | + let _value = this.collection[i]; |
| 34 | + if (_value[1] > priorityItem[1]) { |
| 35 | + this.collection.splice(i, 0, priorityItem); |
| 36 | + inserted = true; |
| 37 | + break; |
| 38 | + } |
| 39 | + } |
| 40 | + if (!inserted) { |
| 41 | + this.collection.push(priorityItem); |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + this.dequeue = function() { |
| 46 | + let val = this.collection.shift(); |
| 47 | + return val[0] |
| 48 | + } |
| 49 | + |
| 50 | + this.size = function() { |
| 51 | + return this.collection.length; |
| 52 | + } |
| 53 | + |
| 54 | + this.isEmpty = function() { |
| 55 | + return this.collection.length === 0; |
| 56 | + } |
| 57 | + |
| 58 | + this.front = function() { |
| 59 | + return this.collection[0] |
| 60 | + } |
| 61 | +} |
0 commit comments