Skip to content

Instantly share code, notes, and snippets.

@ardeshireshghi
Created November 8, 2022 12:37
Show Gist options
  • Save ardeshireshghi/dbf64d0f8cb55df387f90b64045c9817 to your computer and use it in GitHub Desktop.
Save ardeshireshghi/dbf64d0f8cb55df387f90b64045c9817 to your computer and use it in GitHub Desktop.
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