Priority Queue Class

Hi,

So in the coding interview prep > data structures section, on the following challenge

Following is my code

function PriorityQueue () {
  
  this.collection = [];
  this.printCollection = function() {
    console.log(this.collection);
  };
  // Only change code below this line
  this.enqueue = (elem, priority) => {
    let arr = [elem, priority]
    
    if(this.collection.length == 0){      
      return this.collection.push(arr)
    }
    
    if(this.collection.length > 0){
      let priorityList = this.collection.map(e => e[1])
      
      if(priority < priorityList[0]){
        this.collection.unshift(arr)
      }else{
        let i = 1
        while(priority >= priorityList[i]){
          i++
        }
        this.collection.splice(i, 0, arr)
      }

      return this.collection
    }    
    
  }

  this.dequeue = () => {
    let collectionNames = this.collection.map(e => e[0])    
    this.collection.shift()
    return collectionNames.shift()
  }

  this.size = () => {
    return this.collection.length
  }

  this.front = () => {
    return this.collection[0][0]
  }

  this.isEmpty = () => {
    return this.collection.length == 0 ? true : false
  }
  // Only change code above this line
}

So, I don’t understand what is wrong here?

The notes for the test says that:

The enqueue should accept items with the format shown above (['human', 1] ) where 1 represents the priority.

I think the enqueue method needs to be defined with an array as a parameter.

1 Like

Thank you! Modified the code and now it’s working.