js-priority-queue
Version:
Priority queue data structures
63 lines (53 loc) • 1.38 kB
text/coffeescript
module.exports = class BinaryHeapStrategy
constructor: (options) ->
= options?.comparator || (a, b) -> a - b
= 0
= (options.initialValues?.slice(0) || [])
_heapify: ->
if .length > 0
for i in [ 1 ... .length ]
undefined
queue: (value) ->
.push(value)
undefined
dequeue: ->
ret = [0]
last = .pop()
if .length > 0
[0] = last
ret
peek: ->
[0]
clear: ->
= 0
.length = 0
undefined
_bubbleUp: (pos) ->
while pos > 0
parent = (pos - 1) >>> 1
if < 0
x = [parent]; [parent] = [pos]; [pos] = x
pos = parent
else
break
undefined
_bubbleDown: (pos) ->
last = .length - 1
loop
left = (pos << 1) + 1
right = left + 1
minIndex = pos
if left <= last && < 0
minIndex = left
if right <= last && < 0
minIndex = right
if minIndex != pos
x = [minIndex]; [minIndex] = [pos]; [pos] = x
pos = minIndex
else
break
undefined