Create a Priority Queue Class - using sort()

I am trying to use .sort() to greatly simplify this, compared to other solutions I’ve seen. It appears that my collection has the items in the right order by priority and input order, but I’m not passing the isEmpty or first-in-first-out tests ( the last two tests )

function PriorityQueue () {
    this.collection = [];
    this.printCollection = function() {
      console.log(this.collection);
    };
    // Only change code below this line
    this.enqueue = function(arr){
      this.collection.push(arr)
      this.collection.sort((a,b)=>{
        return a[1] - b[1]
      })
      console.log('After enqueue',this.collection)
    }
    this.dequeue = function(){
     this.collection.shift()
     console.log('After dequeue',this.collection)
     return this.collection[0][0]
    }
    this.front = function(){
      console.log('Front',this.collection[0])
      return this.collection[0]
    }
    this.size = function(){
      console.log('Size',this.collection.length)
      return this.collection.length
    }
    this.isEmpty = function(){
      console.log('Empty',this.collection,this.size() === 0)
      return this.size() === 0
    }
    // Only change code above this line
}

const demo = new PriorityQueue()


Any ideas?

@hirodashi Try a test where you enqueue one item and then dequeue it. You will find when you attempt to return this.collection[0][0], that you get an error, because this.collection is an empty array. There would be no such thing as this.collection[0], so it would be undefined and undefined values do not have indexes of 0.

I also suggest using the prototype over this.method Saves on memory.

@RandellDawson @kerafyrm

Thank you both for your input. It now passes all of the tests. I’ll look into prototype method next.

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

const demo = new PriorityQueue()