Advertisement
Guest User

Untitled

a guest
May 20th, 2018
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.55 KB | None | 0 0
  1. // User defined class
  2. // to store element and its priority
  3. class QElement {
  4. constructor(element, priority) {
  5. this.element = element;
  6. this.priority = priority;
  7. }
  8. }
  9.  
  10. // PriorityQueue class
  11. class PriorityQueue {
  12.  
  13. // An array is used to implement priority
  14. constructor() {
  15. this.items = [];
  16. }
  17.  
  18. // enqueue function to add element
  19. // to the queue as per priority
  20. enqueue(element, priority) {
  21. // creating object from queue element
  22. var qElement = new QElement(element, priority);
  23. var contain = false;
  24.  
  25. // iterating through the entire
  26. // item array to add element at the
  27. // correct location of the Queue
  28. for (var i = 0; i < this.items.length; i++) {
  29. if (this.items[i].priority > qElement.priority) {
  30. // Once the correct location is found it is
  31. // enqueued
  32. this.items.splice(i, 0, qElement);
  33. contain = true;
  34. break;
  35. }
  36. }
  37.  
  38. // if the element have the highest priority
  39. // it is added at the end of the queue
  40. if (!contain) {
  41. this.items.push(qElement);
  42. }
  43. }
  44.  
  45. // dequeue method to remove
  46. // element from the queue
  47. dequeue() {
  48. // return the dequeued element
  49. // and remove it.
  50. return this.items.shift();
  51. }
  52. // isEmpty function
  53. isEmpty() {
  54. // return true if the queue is empty.
  55. return this.items.length == 0;
  56. }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement