function swap(heat, index1, index2) {
[heat[index1], heat[index2]] = [heat[index2], heat[index1]]
}
function compare(node1, node2) {
const diff = node1.sortIndex - node2.sortIndex
return diff
}
function push(heat = [], node) {
const index = heat.length
heat.push(node)
siftUp(heat, node, index)
}
function pop(heat) {
const first = heat[0]
if (first !== undefined) {
const last = heat.pop()
if (last !== first) {
heat[0] = last
siftDown(heat, last, 0)
}
} else {
return null
}
}
function siftDown(heat, node, i) {
let index = i
let len = heat.length
while (index < len) {
const leftIndex = (index + 1) * 2 - 1
const left = heat[leftIndex]
const rightIndex = (index + 1) * 2
const right = heat[rightIndex]
if (left !== undefined && compare(left, node) < 0) {
if (right !== undefined && compare(right, left) < 0) {
swap(heat, index, rightIndex)
index = rightIndex
} else {
swap(heat, index, leftIndex)
index = leftIndex
}
} else if (right !== undefined && compare(right, node) < 0) {
heat[index] = right
heat[rightIndex] = node
index = rightIndex
} else {
return
}
}
}
function siftUp(heat, node, index) {
while (true) {
const parentIndex = (index - 1) >>> 1
const parent = heat[parentIndex]
if (parent !== undefined && compare(parent, node) > 0) {
swap(heat, parentIndex, index)
index = parentIndex
} else {
return
}
}
}
function peek(heat) {
const first = heat[0]
return first === undefined ? null : first
}
const a = []
push(a, { sortIndex: 1 })
console.log('peek1',peek(a));
push(a, { sortIndex: 0 })
console.log('peek2',peek(a));
pop(a)
console.log('peek3', peek(a));
push(a, { sortIndex: 2})
push(a, { sortIndex: 4 })
push(a, { sortIndex: 5 })
push(a, { sortIndex: 0 })
push(a, { sortIndex: -1 })
push(a, { sortIndex: 1 })
console.log('a', a)
pop(a)
console.log('a', a)