atriusmaps-node-sdk
Version:
This project provides an API to Atrius Personal Wayfinder maps within a Node environment. See the README.md for more information
71 lines (68 loc) • 1.74 kB
JavaScript
'use strict';
class MinPriorityQueue {
constructor() {
this.heap = [null];
this.heapMap = {};
}
offerWithPriority(node, priority) {
const index = this.heap.push([node, priority]) - 1;
this.heapMap[node] = index;
this.bubble(index);
}
raisePriority(node, priority) {
const index = this.heapMap[node];
this.heap[index][1] = priority;
this.bubble(index);
}
poll() {
if (this.heap.length === 1) {
return null;
}
if (this.heap.length === 2) {
const value2 = this.heap.pop()[0];
delete this.heapMap[value2];
return value2;
}
const value = this.heap[1][0];
delete this.heapMap[value];
this.heap[1] = this.heap.pop();
this.heapMap[this.heap[1][0]] = 1;
this.sink(1);
return value;
}
isEmpty() {
return this.heap.length === 1;
}
bubble(i) {
while (i > 1) {
const parentIndex = i >> 1;
if (!this.isHigherPriority(i, parentIndex)) {
break;
}
this.swap(i, parentIndex);
i = parentIndex;
}
}
sink(i) {
while (i * 2 < this.heap.length) {
const isRightChildHigherPriority = this.heap[i * 2 + 1] === void 0 ? false : this.isHigherPriority(i * 2 + 1, i * 2);
const childIndex = isRightChildHigherPriority ? i * 2 + 1 : i * 2;
if (this.isHigherPriority(i, childIndex)) {
break;
}
this.swap(i, childIndex);
i = childIndex;
}
}
swap(i, j) {
this.heapMap[this.heap[i][0]] = j;
this.heapMap[this.heap[j][0]] = i;
const temp = this.heap[i];
this.heap[i] = this.heap[j];
this.heap[j] = temp;
}
isHigherPriority(i, j) {
return this.heap[i][1] < this.heap[j][1];
}
}
module.exports = MinPriorityQueue;