algorithmpool
Version:
A pool of algorithms and data-structures for geeks
81 lines (72 loc) • 2.17 kB
JavaScript
export class priorityQueue {
constructor(){
this.elements = [];
this.offset = 0;
this.priorities = {};
}
length(){
return this.elements.length - this.offset;
}
isEmpty(){
return this.length() === 0;
}
toArray(){
const arr = [];
if (this.isEmpty()) {
return arr;
}
const pKeys = Object.keys(this.priorities);
for (let i = offset; i < pKeys.length; i += 1) {
arr.push(this.elements[this.priorities[pKeys[i]]]);
}
return arr;
};
clear() {
this.elements = [];
this.offset = 0;
this.priorities = {};
};
front(){
if (!this.isEmpty()) {
const pKeys = Object.keys(this.priorities);
const firstIndex = this.priorities[pKeys[this.offset]];
return this.elements[firstIndex];
}
return null;
};
back(){
if (!this.isEmpty()) {
const pKeys = Object.keys(this.priorities);
const lastIndex = this.priorities[pKeys[pKeys.length - 1]];
return this.elements[lastIndex];
}
return null;
};
enqueue(el, priority){
if (Number.isNaN(+priority) || priority < 1) {
throw new Error('priority should be a positive number');
}
this.elements.push(el);
this.priorities[priority] = this.elements.length - 1;
};
dequeue(){
if (!this.isEmpty()) {
const first = front();
this.offset += 1;
if (this.offset * 2 >= this.elements.length) {
const pKeys = Object.keys(this.priorities);
const els = [];
const prs = {};
for (let i = this.offset; i < this.elements.length; i += 1) {
els.push(this.elements[this.priorities[pKeys[i]]]);
prs[this.priorities[i]] = els.length - 1;
}
this.priorities = prs;
this.elements = els;
this.offset = 0;
}
return first;
}
return null;
};
}