The challenge is:
Coding Interview Prep > Data Structures > Create a Priority Queue Class
My code is:
function PriorityQueue () {
this.collection = [];
this.printCollection = function() {
console.log(this.collection);
};
// Only change code below this line
this.enqueue = function(arr) {
if (this.collection.length === 0) {
this.collection.push(arr);
} else {
let inserted = false;
for (let i = 0; i <= this.collection.length-1; i++) {
if (this.collection[i][1] > arr[1]) {
this.collection.splice(i, 0, arr);
inserted = true;
break;
}
}
if (inserted == false) {
this.collection.push(arr);
}
}
}
this.dequeue = function() {
return this.collection.shift();
}
this.size = function() {
return this.collection.length;
}
this.front = function() {
return this.collection[this.collection.length-1];
}
this.isEmpty = function() {
return (this.collection.length === 0);
}
// Only change code above this line
}
// tests
let pq = new PriorityQueue;
pq.enqueue(["gialbo", 3]);
pq.enqueue(["peccanza", 1]);
pq.enqueue(["limonds", 4]);
pq.enqueue(["forrettini", 2]);
pq.enqueue(["gualuap", 5]);
pq.printCollection()
let d = pq.dequeue();
let f = pq.front();
console.log("d = ", d, " f = ", f);
console.log("size = ", pq.size(), " is empty =",pq.isEmpty());
It seems to me that the tests I put at the bottom of the code give correct results, but the system tests return the following errors
The front method should return the correct item at the
front of the queue as items are enqueued and dequeued.
The priority queue should return items with a higher
priority before items with a lower priority and return
items in first-in-first-out order otherwise.
The thing is, maybe I can’t understand what the challenge is asking.