SHARE
TWEET

Untitled

a guest May 25th, 2019 75 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class PriorityQueue {
  2.    constructor(maxSize) {
  3.       // Set default max size if not provided
  4.       if (isNaN(maxSize)) {
  5.          maxSize = 10;
  6.        }
  7.       this.maxSize = maxSize;
  8.       // Init an array that'll contain the queue values.
  9.       this.container = [];
  10.    }
  11.    // Helper function to display all values while developing
  12.    display() {
  13.       console.log(this.container);
  14.    }
  15.    // Checks if queue is empty
  16.    isEmpty() {
  17.       return this.container.length === 0;
  18.    }
  19.    // checks if queue is full
  20.    isFull() {
  21.       return this.container.length >= this.maxSize;
  22.    }
  23.    enqueue(data, priority) {
  24.       // Check if Queue is full
  25.       if (this.isFull()) {
  26.          console.log("Queue Overflow!");
  27.          return;
  28.       }
  29.       let currElem = new this.Element(data, priority);
  30.       let addedFlag = false;
  31.       // Since we want to add elements to end, we'll just push them.
  32.       for (let i = 0; i < this.container.length; i++) {
  33.          if (currElem.priority < this.container[i].priority) {
  34.             this.container.splice(i, 0, currElem);
  35.             addedFlag = true; break;
  36.          }
  37.       }
  38.       if (!addedFlag) {
  39.          this.container.push(currElem);
  40.       }
  41.    }
  42.    dequeue() {
  43.    // Check if empty
  44.    if (this.isEmpty()) {
  45.       console.log("Queue Underflow!");
  46.       return;
  47.    }
  48.    return this.container.pop();
  49. }
  50. peek() {
  51.    if (isEmpty()) {
  52.       console.log("Queue Underflow!");
  53.       return;
  54.    }
  55.    return this.container[this.container.length - 1];
  56. }
  57. clear() {
  58.    this.container = [];
  59.    }
  60. }
  61. // Create an inner class that we'll us
  62.  
  63. e to create new nodes in the queue
  64. // Each element has some data and a priority
  65. PriorityQueue.prototype.Element = class {
  66.    constructor(data, priority) {
  67.       this.data = data;
  68.       this.priority = priority;
  69.    }
  70. };
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top