Data Structures - Create a Priority Queue Class

Tell us what’s happening:
Describe your issue in detail here.
The front method should return the correct item at the front of the queue as items are enqueued and dequeued.
I dont see what the issue is?

Your code so far

function PriorityQueue () {
  this.collection = [];
  this.printCollection = function() {
    console.log(this.collection);
  };
  // Only change code below this line
  this.enqueue = function(val) {
    this.collection.unshift(val);
    this.collection.sort(function(a, b){return b[1] - a[1]})
  };
  this.dequeue = function() {
    return this.collection.pop();
  };
  this.size = function() {
    return this.collection.length;
  };
  this.front = function() {
    return this.collection[collection.length-1];
  };
  this.isEmpty = function() {
    return this.collection.length===0;
  };
  
  // Only change code above this line
}

**Your browser information:**

User Agent is: <code>Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36</code>

**Challenge:** Data Structures - Create a Priority Queue Class

**Link to the challenge:**
https://www.freecodecamp.org/learn/coding-interview-prep/data-structures/create-a-priority-queue-class

You’re returning the item at the end, not the front. You’re also returning a pair of the item + the priority, not the item.

Its still not happy with the first element this.collection[0][0]
Is this expecting the collection to have unsorted values and we should only sort it during retrival?

Its still not happy with the first element this.collection[0][0]
Is this expecting the collection to have unsorted values and we should only sort it during retrival?

function PriorityQueue () {
  this.collection = [];
  this.printCollection = function() {
    console.log(this.collection);
  };
  // Only change code below this line
  this.enqueue = function(val) {

    this.collection.unshift(val);
    //this.collection.sort(function(a, b){return b[1] - a[1]})
  };
  this.dequeue = function() {
  let val = this.collection;
  val.sort(function(a, b){return b[1] - a[1]});
    //return this.collection.pop()[0];
    return val[0];
  };
  this.size = function() {
    return this.collection.length;
  };
  this.front = function() {
    let val = this.collection;
    val.sort(function(a, b){return b[1] - a[1]});
    return val[val.length-1][0];
    //return this.collection[0][0];
  };
  this.isEmpty = function() {
    return this.collection.length===0;
  };
  
  // Only change code above this line
}

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.