JSFiddle - React, Tailwind, and code Playground

by honnza

HTML

<canvas id=c width=200 height=200>

CSS

#c{box-shadow:0 0 5px};

JavaScript

"strict mode"

// classes /////////////////////////////////////////////////////////////////////

function PriorityQueue(){
  this.heap = [undefined];   // [1..n -> entry]
  this.lookup = {}; // {key  -> index}
}

/* entry = {priority, key} */
PriorityQueue.prototype.push = function(entry){
  var i = this.lookup[entry.key] || this.heap.length;
  while(i > 1 && this.heap[i>>1].priority > entry.priority){
    this.heap[i] = this.heap[i>>1];
    this.lookup[this.heap[i].key] = i;
    i = i>>1;
  }
  this.heap[i] = entry;
  this.lookup[entry.key] = i;
  this.log("heap after push:");
}

PriorityQueue.prototype.pop = function(){
  if(this.empty()) throw "empty queue";
  var retval = this.heap[1];
  delete this.heap[retval.name];
  var bubble = this.heap.pop();
  if(this.empty()){
    console.log("queue empty after pop");
    return retval;
  }
  var i = 1;
  while(true){
    var dir = 0;
    if(this.heap.length <= 2*i) break;
    if(
         this.heap.length > 2*i+1
      && this.heap[2*i+1].priority < this.heap[2*i].priority
    ){
      dir = 1;
    }
    if(this.heap[2*i+dir].priority > bubble.priority) break;
    
    this.heap[i] = this.heap[2*i+dir];
    this.lookup[this.heap[i].key] = i;
    i = 2*i+dir;
  }
  this.heap[i] = bubble;
  this.lookup[bubble.key] = i;
  this.log("heap after pop:");
  return retval;
}

PriorityQueue.prototype.find = function(name){
  return lookup[name];
}

PriorityQueue.prototype.log = function(prefix){
  console.log(prefix + this.heap.map(function(x,i){
    return ((i&i-1) ? " " : "  ") + (x && x.priority)
  }).join());
}

PriorityQueue.prototype.empty = function(){return this.heap.length < 2};

// // // // // // // // // // // // // // // // // // // // // // // // // // //

function aStar2DMap (xFrom, yFrom, xTo, yTo, costmap, mincost){
  function d(x1, y1, x2, y2){return Math.max(Math.abs(x1-x2),Math.abs(y1-y2))}

  dx = [-1,  0,  1,  0, -1, -1,  1,  1];
  dy = [ 0, -1,  0,  1, -1,  1,  1, -1];
  var lookup = {};
  var pq = new...