My code for priority queue is failing one test: “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.”
Not sure of the reason why, but I’ve checked the queue and it’s the order I’m expecting. Tried resetting the challenge and resubmitting the code but still the same.
Here is my code:
function PriorityQueue () {
this.collection = [];
this.printCollection = function() {
console.log(this.collection);
};
// Only change code below this line
var n = this.collection.length;
this.enqueue = function(newItem) {
if (n == 0 && this.collection.indexOf(newItem) == -1) {
this.collection.splice(0, 0, newItem);
n = this.collection.length;
} else {
this.collection.forEach((x, index) => {
if (x[1] > newItem[1] && this.collection.indexOf(newItem) == -1) { // If item in collection has bigger priority value than newItem priority value
this.collection.splice(index, 0, newItem);
n = this.collection.length;
} else { // If item in collection has lesser priority value than newItem priority value
if (index + 1 == n && this.collection.indexOf(newItem) == -1) {
this.collection.splice(index + 1, 0, newItem);
n = this.collection.length;
}
}
});
}
this.collection.forEach((y) => {
console.log(y);
});
}
this.dequeue = function() {
var removedElem = this.collection.shift();
n = this.collection.length;
return removedElem;
}
this.size = function() {
return n;
}
this.front = function() {
return this.collection[0];
}
this.isEmpty = function() {
if (n == 0) {
return true;
}
return false;
}
// Only change code above this line
}