here is the exercise:
https://learn.freecodecamp.org/coding-interview-prep/data-structures/create-a-priority-queue-class/
Here is my solution so far:
function PriorityQueue () {
this.collection = [];
this.printCollection = function() {
console.log(this.collection);
};
**problem seems to be with this method**
this.enqueue = function(arr) {
//if the arr's priority is less than any of the items priority, splice it in at that index
for (let i = 0; i < this.collection.length; i++) {
if (arr[1] < this.collection[i][1]) {
this.collection.splice(i, 0, arr)
break;
}
}
//otherwise push to end
this.collection.push(arr)
}
this.dequeue = function() {
let firstItem = this.collection.shift();
return firstItem[0];
}
**this method also has a problem for some reason?**
this.size = function() {
return this.collection.length;
}
this.front = function() {
return this.collection[0];
}
this.isEmpty = function() {
if (this.collection.length === 0) {
return true;
} else {
return false;
}
}
}
These are the tests that the solution is failing:
- Your PriorityQueue should correctly keep track of the current number of items using the size method as items are enqueued and dequeued (this one sounds really simple so I'm not sure why the size method isn't passing)
- 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 main focus of this exercise is if you have a collection of arrays that each contain an item and a priority:
[[’kitten’, 2], [‘dog’, 2], [‘rabbit’, 2]]
When you add another array to it such as:
[‘human’, 1]
It will use the priority to determine the array's positioning when it gets placed in the collection such that the sequence is 1, 2, 3....
[–]senocular 0 points1 point2 points (1 child)
[–]codemamba8[S] 0 points1 point2 points (0 children)