Priority Queue: cannot see what is wrong with the code

Hi,
I don’t see it. As far as I can tell the code works. Maybe I’ve misunderstood the assignment? I am not passing

The front method should return the correct item at the front of the queue as items are enqueued and dequeued.

and the last one :

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.

1 being the highest priority and 2 being a priority lower, as is the case in the example.


function PriorityQueue () {
this.collection = [];
this.printCollection = function() {
  console.log(this.collection);
};
// Only change code below this line
this.enqueue = (el, prior=1) => {
  if(this.collection.length === 0) {
     return this.collection.push([el, prior])
  } 
  else if(prior < this.collection[0][1]) {
    return this.collection.unshift([el, prior]);
  }  
  else {
    for(let i = 0; i < this.collection.length; i++) {
      let item = this.collection[i][1];
      if(item < prior || prior === item) {
        if(i < this.collection.length-1 && prior < this.collection[i+1][1]) {
          return this.collection.splice(i+1, 0, [el, prior]);
        } else if(i === this.collection.length-1) {
          return this.collection.push([el, prior]);
        }
      } else { return this.collection.splice(i+1, 0, [el, prior])} 
    } 
  }
}
this.dequeue = () => this.collection.shift();
this.size = () => this.collection.length; 
this.front = () => this.collection[0][0];
this.isEmpty = () => (this.collection.length === 0) ? true : false;
// Only change code above this line
}

Your browser information:

User Agent is: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:81.0) Gecko/20100101 Firefox/81.0.

Challenge: Create a Priority Queue Class

Link to the challenge:

Is part of the problem. You’re passing in arrays like ['a', 1] in the argument el in the function call.

Then here, you are pushing on [['a', 1], 1]. This will lead to unexpected output during testing. There are several places where arrays are being nested too deeply.

Try adding a this.printCollection() at the beginning of this.enqueue() to see what is going on with your queue during the tests.

1 Like

Thank you very much for your remark. I did misunderstand the assignment.
I have been passing in a string and a number instead of an array. The code works but is not what is required. I was calling the function like this : books(“Foundation”, 1) and I should do this : books([“Foundation”, 1])

The enqueue should accept items with the format shown above ( ['human', 1] ) where 1 represents the priority. dequeue and front should return only the item’s name, not its priority.

It’s always the same. 90% of my problems stem from the fact that I just don’t read what it says.

I’m passing all criteria now.

Thank you very much!