3.3.0 • Published 3 years ago

binary-heap.js v3.3.0

Weekly downloads
136
License
ISC
Repository
github
Last release
3 years ago

Binary heap

A package for general purpose binary heap data structure that can contain any type of data

Installation

npm i binary-heap.js

Constructor

ParameterTypeRequiredDefaultDescription
extractorfunctionfalsefunction that extracts the key used for sorting elements in the heap (should be equal to identity for primitive data types)

Methods

NameDescriptionReturn
InsertInsert a single element into the heapvoid
InsertManyInserts Many elements into the heapvoid
popPops the top element (maximum or minimum depending on the type of the heap)type T (type of elements inserted)
isEmptyChecks if the heap is empty or notboolean

Usage

const maxHeap = new MaxHeap( (x) =>x );
maxHeap.insert(3);
maxHeap.insertMany([5,7].values())

maxHeap.pop() // 7
maxHeap.pop() // 5
maxHeap.pop() // 3
maxHeap.pop() // undefined

const minHeap = new MinHeap( (x) =>x );

maxHeap.insert(5);
maxHeap.insertMany([3,7].values())

maxHeap.pop() // 3
maxHeap.pop() // 5
maxHeap.pop() // 7
maxHeap.pop() // undefined

Works with any data structure that implements the iteratable interface to provide it's elements

// Works with arrays, maps, sets
const arr = [1,2,3];
const set = new Set([1,2,3])
const map = new Map();
map.set(1,1)
map.set(2,2)
map.set(3,3);

const maxHeapOne = new MaxHeap((x) =>x);
maxHeapOne.insertMany(arr.values());

const maxHeapTwo = new MaxHeap((x) =>x);
maxHeapTwo.insertMany(set.values());

const maxHeapThree = new MaxHeap((x) =>x);
maxHeapThree.insertMany(map.keys().values());

Works with complex objects as long as you provide the right extractor

const arr = [{id:1},{id:2},{id:3}];

const maxHeap = new MaxHeap((x) =>x.id);
maxHeap.insertMany(arr.values());
3.2.2

3 years ago

3.3.0

3 years ago

3.2.1

3 years ago

3.2.0

3 years ago

3.1.1

3 years ago

3.1.0

3 years ago

3.0.0

3 years ago

2.0.0

3 years ago

1.2.0

3 years ago

1.1.0

3 years ago

1.0.0

3 years ago