My code below:
(Updated Feb 7th 16:40)
function PriorityQueue () {
this.collection = [];
this.printCollection = function() {
console.log(this.collection);
};
this.enqueue = (item) => {
if(this.collection.length == 0){
this.collection.push(item)
}
else{
for(let i=0; i<this.collection.length; i++){
if(this.collection[i][1] < item[1]){
this.collection.splice(i,0,item)
break
}
if(i == this.collection.length-1){
this.collection.push(item)
break
}
}
}
}
this.dequeue = () => {
return this.collection.shift()
}
this.size = () => {
return this.collection.length
}
this.front = () => {
return this.collection[0]
}
this.isEmpty = () => {
if(this.collection.length === 0){
return true
}
else{
return false
}
}
}
Failing the following 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.
My thoughts:
I’ve tried changing my code to either display 1,2,3, or 3,2,1 by ascending or descending priority, either way, my code is being judged as wrong by the test.
Ascending or Descending + First-In-First-Out
My code can be simply be changed to ascending or descending priority by changing the comparative > operator to < in the for loop. First-in-first-out is also considered and working fine.
Test Result (Descending order)
var test = new PriorityQueue()
test.enqueue(['Codey', 2]);
test.enqueue(['Ken', 1]);
test.enqueue(['Hamster', 1]);
test.enqueue(['Nintendo', 1])
test.enqueue(['Dreamcast', 2])
console.log(test.collection)
[ [ 'Codey', 2 ],
[ 'Dreamcast', 2 ],
[ 'Ken', 1 ],
[ 'Hamster', 1 ],
[ 'Nintendo', 1 ] ]
Any comment is appreciated, thanks.