typescript-ds-lib
Version:
A collection of TypeScript data structure implementations
116 lines • 3.38 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Heap = void 0;
const base_collection_1 = require("./base-collection");
const utils_1 = require("./utils");
class Heap extends base_collection_1.BaseCollection {
items;
comparator;
constructor(comparator = (a, b) => a < b) {
super();
this.items = [];
this.comparator = comparator;
}
/**
* Adds an element to the heap.
*/
push(element) {
this.items.push(element);
this.heapifyUp(this.items.length - 1);
}
/**
* Removes and returns the root element from the heap, or undefined if heap is empty.
*/
pop() {
if (this.isEmpty()) {
return undefined;
}
const root = this.items[0];
const lastElement = this.items.pop();
if (!this.isEmpty()) {
this.items[0] = lastElement;
this.heapifyDown(0);
}
return root;
}
/**
* Returns the root element without removing it, or undefined if heap is empty.
*/
top() {
return this.items[0];
}
/**
* Checks if the heap is empty. Returns true if empty, false otherwise.
*/
isEmpty() {
return this.items.length === 0;
}
/**
* Returns the number of elements in the heap.
*/
size() {
return this.items.length;
}
/**
* Removes all elements from the heap.
*/
clear() {
this.items = [];
}
/**
* Moves an element up the heap to its correct position.
*/
heapifyUp(index) {
while (index > 0) {
const parentIndex = Math.floor((index - 1) / 2);
if (this.comparator(this.items[index], this.items[parentIndex])) {
[this.items[index], this.items[parentIndex]] =
[this.items[parentIndex], this.items[index]];
index = parentIndex;
}
else {
break;
}
}
}
/**
* Moves an element down the heap to its correct position.
*/
heapifyDown(index) {
while (true) {
let smallestIndex = index;
const leftChild = 2 * index + 1;
const rightChild = 2 * index + 2;
if (leftChild < this.items.length &&
this.comparator(this.items[leftChild], this.items[smallestIndex])) {
smallestIndex = leftChild;
}
if (rightChild < this.items.length &&
this.comparator(this.items[rightChild], this.items[smallestIndex])) {
smallestIndex = rightChild;
}
if (smallestIndex === index) {
break;
}
[this.items[index], this.items[smallestIndex]] =
[this.items[smallestIndex], this.items[index]];
index = smallestIndex;
}
}
/**
* Checks if two heaps are equal.
*/
equals(other) {
if (!other || !(other instanceof Heap))
return false;
if (this.size() !== other.size())
return false;
for (let i = 0; i < this.items.length; i++) {
if (!utils_1.Utils.equals(this.items[i], other.items[i]))
return false;
}
return true;
}
}
exports.Heap = Heap;
//# sourceMappingURL=heap.js.map