Created
November 8, 2022 12:37
-
-
Save ardeshireshghi/dbf64d0f8cb55df387f90b64045c9817 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function PriorityQueue() { | |
this.collection = []; | |
} | |
PriorityQueue.prototype = { | |
enqueue([item, priority]) { | |
let indexToBePlacedAt = -1; | |
for (let i = 0; i < this.collection.length; i++) { | |
const [, itemPriority] = this.collection[i]; | |
const isNewItemHigherPriority = priority < itemPriority; | |
if (isNewItemHigherPriority) { | |
indexToBePlacedAt = i; | |
} else { | |
break; | |
} | |
} | |
if (indexToBePlacedAt > -1) { | |
this.collection.splice(indexToBePlacedAt + 1, 0, [item, priority]); | |
} else { | |
this.collection.unshift([item, priority]); | |
} | |
}, | |
front() { | |
return this.isEmpty() ? undefined : this.collection[this.size() - 1][0]; | |
}, | |
dequeue() { | |
const itemToDequeue = this.collection.pop(); | |
return itemToDequeue ? itemToDequeue[0] : undefined; | |
}, | |
size() { | |
return this.collection.length; | |
}, | |
isEmpty() { | |
return this.size() === 0; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment