Skip to content

Instantly share code, notes, and snippets.

@gladchinda
Last active October 8, 2022 08:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gladchinda/c717a4224ae9574e2cdf7a01ea8347ab to your computer and use it in GitHub Desktop.
Save gladchinda/c717a4224ae9574e2cdf7a01ea8347ab to your computer and use it in GitHub Desktop.
Binary heap implementation for JavaScript
const swap = (arr, index1, index2) => {
const tmp = arr[index1];
arr[index1] = arr[index2];
arr[index2] = tmp;
};
const sift_down = (heap, cmp, index) => {
const item = heap[index];
const size = heap.length;
while (index - size < 0) {
let child = 2 * index + 2;
if (child - size >= 0 || cmp(heap[child - 1], heap[child]) <= 0) {
--child;
}
if (child - size < 0 && cmp(item, heap[child]) > 0) {
swap(heap, index, child);
index = child;
} else break;
}
return index;
};
const sift_up = (heap, cmp, index) => {
const item = heap[index];
while (index) {
const parent = Math.floor((index - 1) / 2);
if (parent && cmp(heap[parent], item) > 0) {
heap[index] = heap[parent];
index = parent;
} else break;
}
return (heap[index] = item, index);
};
export default function Heap(comparator) {
if (!(this instanceof Heap)) {
return new Heap(comparator);
}
if (typeof comparator !== "function") {
comparator = (a, b) => (a - b) || 0;
}
const heap = [];
const extract = (...args) => {
const index = +(args.length && heap.findIndex(item => item === args[0]));
if (index >= 0) {
swap(heap, index, heap.length - 1);
const item = heap.pop();
return (sift_down(heap, comparator, index), item);
}
return null;
};
const insert = item => {
sift_up(heap, comparator, heap.push(item) - 1);
};
Object.defineProperties(this, {
peak: { get: () => heap[0] },
empty: { get: () => heap.length === 0 },
extract: { enumerable: true, value: extract },
insert: { enumerable: true, value: insert }
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment