Advertisement
Guest User

Untitled

a guest
Jul 23rd, 2019
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function PriorityQueue () {
  2.     this.collection = []
  3.     this.collectionObj = {}
  4.     this.printCollection = function() {
  5.       console.table(this.collection)
  6.     }
  7.  
  8.     this.enqueue = ([str, prio]) => {
  9.  
  10.         if (this.isEmpty()) {
  11.             this.collectionObj[prio] = [str]
  12.             this.collection.push([str, +prio])
  13.             return
  14.         }
  15.  
  16.         if (!this.collectionObj[prio]) {
  17.             this.collectionObj[prio] = [str]
  18.         } else {
  19.             this.collectionObj[prio].push(str)
  20.         }
  21.        
  22.         this.collection = []
  23.         let keys = Object.keys(this.collectionObj)
  24.  
  25.         keys.map(key => {
  26.             if (this.collectionObj[key].length === 1) {
  27.                 this.collection.push([this.collectionObj[key][0], +key])
  28.             } else {
  29.                 this.collectionObj[key].map(str => this.collection.push([str, +key]) )
  30.             }
  31.  
  32.         })
  33.     }
  34.    
  35.     this.dequeue = () => {
  36.         let keys = Object.keys(this.collectionObj)
  37.         let elToReturn
  38.        
  39.         if (this.collectionObj[keys[0]].length === 1) {
  40.             elToReturn = this.collectionObj[keys[0]]
  41.             delete this.collectionObj[keys[0]]
  42.             this.collection.shift()
  43.         } else {
  44.             elToReturn = this.collectionObj[keys[0]][0]
  45.             this.collectionObj[keys[0]].shift()
  46.             this.collection.shift()
  47.         }
  48.  
  49.         return elToReturn
  50.     }
  51.  
  52.     this.front = () => this.collection[0]
  53.     this.size = () => this.collection.length
  54.     this.isEmpty = () => this.collection.length === 0
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement