Peeking elements from a PriorityQueue using JavaScript


Peeking a PriorityQueue means getting the value with the highest priority without removing it. So we can implement the peek function as follows &minusl 

Example

peek() {
   if (isEmpty()) {
      console.log("Queue Underflow!");
      return;
   }
   return this.container[this.container.length - 1];
}

You can check if this function is working fine using − 

Example

let q = new PriorityQueue(4);
q.enqueue("Hello", 3);
q.enqueue("World", 2);
q.enqueue("Foo", 8);
console.log(q.peek());
q.display();

Output

This will give the output −

{ data: 'Foo', priority: 8 }
[ { data: 'World', priority: 2 },
   { data: 'Hello', priority: 3 },
   { data: 'Foo', priority: 8 } ]

As you can see here, peek() differs from dequeue in that it just returns the front value without removing it.

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 15-Jun-2020

81 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements