Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function PriorityQueue () {
- this.collection = []
- this.collectionObj = {}
- this.printCollection = function() {
- console.table(this.collection)
- }
- this.enqueue = ([str, prio]) => {
- if (this.isEmpty()) {
- this.collectionObj[prio] = [str]
- this.collection.push([str, +prio])
- return
- }
- if (!this.collectionObj[prio]) {
- this.collectionObj[prio] = [str]
- } else {
- this.collectionObj[prio].push(str)
- }
- this.collection = []
- let keys = Object.keys(this.collectionObj)
- keys.map(key => {
- if (this.collectionObj[key].length === 1) {
- this.collection.push([this.collectionObj[key][0], +key])
- } else {
- this.collectionObj[key].map(str => this.collection.push([str, +key]) )
- }
- })
- }
- this.dequeue = () => {
- let keys = Object.keys(this.collectionObj)
- let elToReturn
- if (this.collectionObj[keys[0]].length === 1) {
- elToReturn = this.collectionObj[keys[0]]
- delete this.collectionObj[keys[0]]
- this.collection.shift()
- } else {
- elToReturn = this.collectionObj[keys[0]][0]
- this.collectionObj[keys[0]].shift()
- this.collection.shift()
- }
- return elToReturn
- }
- this.front = () => this.collection[0]
- this.size = () => this.collection.length
- this.isEmpty = () => this.collection.length === 0
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement