Last active
November 6, 2019 22:40
-
-
Save jacobstern/7d84bfff3442d58a98ea605f22caf1d2 to your computer and use it in GitHub Desktop.
Source snippet from mourner/tinyqueue
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
Excerpted from https://github.com/mourner/tinyqueue | |
Copyright (c) 2017, Vladimir Agafonkin | |
Permission to use, copy, modify, and/or distribute this software for any purpose | |
with or without fee is hereby granted, provided that the above copyright notice | |
and this permission notice appear in all copies. | |
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH | |
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND | |
FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, | |
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS | |
OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER | |
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF | |
THIS SOFTWARE. | |
*/ | |
class TinyQueue { | |
constructor(data = [], compare = defaultCompare) { | |
this.data = data; | |
this.length = this.data.length; | |
this.compare = compare; | |
if (this.length > 0) { | |
for (let i = (this.length >> 1) - 1; i >= 0; i--) this._down(i); | |
} | |
} | |
push(item) { | |
this.data.push(item); | |
this.length++; | |
this._up(this.length - 1); | |
} | |
pop() { | |
if (this.length === 0) return undefined; | |
const top = this.data[0]; | |
const bottom = this.data.pop(); | |
this.length--; | |
if (this.length > 0) { | |
this.data[0] = bottom; | |
this._down(0); | |
} | |
return top; | |
} | |
peek() { | |
return this.data[0]; | |
} | |
_up(pos) { | |
const {data, compare} = this; | |
const item = data[pos]; | |
while (pos > 0) { | |
const parent = (pos - 1) >> 1; | |
const current = data[parent]; | |
if (compare(item, current) >= 0) break; | |
data[pos] = current; | |
pos = parent; | |
} | |
data[pos] = item; | |
} | |
_down(pos) { | |
const {data, compare} = this; | |
const halfLength = this.length >> 1; | |
const item = data[pos]; | |
while (pos < halfLength) { | |
let left = (pos << 1) + 1; | |
let best = data[left]; | |
const right = left + 1; | |
if (right < this.length && compare(data[right], best) < 0) { | |
left = right; | |
best = data[right]; | |
} | |
if (compare(best, item) >= 0) break; | |
data[pos] = best; | |
pos = left; | |
} | |
data[pos] = item; | |
} | |
} | |
function defaultCompare(a, b) { | |
return a < b ? -1 : a > b ? 1 : 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment