react-flexigrid
Version:
A React table component designed to allow presenting millions of rows of data.
113 lines (90 loc) • 2.76 kB
JavaScript
import _classCallCheck from "babel-runtime/helpers/classCallCheck";
var defaultComparator = function defaultComparator(a, b) {
return a < b;
};
var Heap = function () {
function Heap(items, comparator) {
_classCallCheck(this, Heap);
this.items = items || [];
this.size = this.items.length;
this.comparator = comparator || defaultComparator;
// heapify
for (var i = Math.floor((this.size + 1) / 2); i >= 0; i -= 1) {
this.sinkDown(i);
}
}
Heap.prototype.isEmpty = function isEmpty() {
return this.size === 0;
};
Heap.prototype.getSize = function getSize() {
return this.size;
};
Heap.prototype.peek = function peek() {
return this.size > 0 ? this.items[0] : null;
};
Heap.prototype.pop = function pop() {
if (this.size === 0) {
return null;
}
var currentItem = this.items[0];
var lastItem = this.items.pop();
this.size -= 1;
if (this.size > 0) {
this.items[0] = lastItem;
this.sinkDown(0);
}
return currentItem;
};
Heap.prototype.push = function push(item) {
this.items[this.size] = item;
this.size += 1;
this.bubbleUp(this.size - 1);
};
Heap.prototype.bubbleUp = function bubbleUp(index) {
var currentItem = this.items[index];
while (index > 0) {
var parentIndex = Math.floor((index + 1) / 2) - 1;
var parentItem = this.items[parentIndex];
// if parentItem < currentItem, stop
if (this.comparator(parentItem, currentItem)) {
return;
}
// swap
this.items[parentIndex] = currentItem;
this.items[index] = parentItem;
index = parentIndex; // eslint-disable-line
}
};
Heap.prototype.sinkDown = function sinkDown(index) {
var currentItem = this.items[index];
while (true) {
// eslint-disable-line
var leftChildIndex = 2 * (index + 1) - 1;
var rightChildIndex = 2 * (index + 1);
var swapIndex = -1;
if (leftChildIndex < this.size) {
var leftChild = this.items[leftChildIndex];
if (this.comparator(leftChild, currentItem)) {
swapIndex = leftChildIndex;
}
}
if (rightChildIndex < this.size) {
var rightChild = this.items[rightChildIndex];
if (this.comparator(rightChild, currentItem)) {
if (swapIndex === -1 || this.comparator(rightChild, this.items[swapIndex])) {
swapIndex = rightChildIndex;
}
}
}
// if we don't have a swap, stop
if (swapIndex === -1) {
return;
}
this.items[index] = this.items[swapIndex];
this.items[swapIndex] = currentItem;
index = swapIndex; // eslint-disable-line
}
};
return Heap;
}();
export default Heap;