mourner / tinyqueue

The smallest and simplest priority queue in JavaScript.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Bug: down() use a wrong length

Incubatio opened this issue · comments

For some reason i had to replace some old PriorityQueue I was using in my game (for pathfinding) in favor of a new one.
I wanted something small and it's why I chose tinyQueue.

However after a simple port to another haxe, I had the lib crashing on that line:

  if (right < this.length && compare(data[right], best) < 0) {

The problem is that this.length is decremented after using _down(0), leading to a situation where _down function uses an incorrect length, resulting in data[right] being undefined and crashing the game.

Below you can see when _length get inconsistent, between the data.pop and length--:

  // from pop()
  // [...]
  const bottom = this.data.pop();
  if (this.length > 1) {
    this.data[0] = bottom;
    this._down(0);
  }
  this.length--;
  // [...]

As soon as I moved this.length--; under const bottom = this.data.pop();, problem was fixed.

Note that even if on my haxe app i get an Error, it's probable that it will be silent in JS, as:

  • JS array can access unexisting key, ex: [][-1] or [][100] will not trigger an error and will be undefined.
  • comparaison with undefined somehow works, ex: 3 < undefined is false

I'm not remotely sure if that could even be a bug in a running js app, but better be safe than sorry ;).

Great catch! Would you submit a PR with a fix?

Sorry i found other bugs with tinyqueue and i have not time to investigate them.
So I switched to https://github.com/adamhooper/js-priority-queue and so far it works out of the box.
Also their unit test and perf test seem solid.