ts-treemap
a TypeScript implementation of TreeMap
You can use some features of TreeMap in Java with TypeScript.
Installation
npm i ts-treemap --save
Usage
Create New TreeMap and Add Entries
// add new entrytreeMap.set10, 'abc'treeMap.set5, 'def'treeMap.set0, 'ghi' // you can also create new TreeMap with iterable
Get Entry from TreeMap
// get first entrytreeMap.firstEntry // [0, 'ghi'] // get entry nearest to key '7'treeMap.floorEntry7 // [5, 'def']treeMap.ceilingEntry7 // [10, 'abc'] treeMap.higherEntry5 // [10, 'abc']treeMap.lowerEntry5 // [0, 'ghi']
Duplicate a Map
// copy map // copy as Map object // create TreeMap from Map
Note
In order to sort keys, you need to define a comparison function, and TreeMap has an internal comparison function that automatically sorts keys each time you add them.
The ES2015 Map uses the "Same-value-zero" algorithm to determine if there are duplicate keys when an entry is added. The algorithm uses "===" to determine equivalence when comparing objects (but +0 and -0 are considered equal). This means that when you add multiple entries with the same key, the duplicate check will not work correctly if the type of key is object (such as Date
).
To avoid this problem, TreeMap does not use that algorithm when adding keys, but uses a comparison function. If the return value of the comparison function is 0, the key is considered to be a duplicate.
This comparison function conforms to the compare function used in Array.prototype.sort()
.
You don’t have to define the compare function if the type of the key is number
, string
or Date
.
If you want to use other types as keys, you can use one of the following methods to generate a TreeMap.
Method 1: Pass the comparison function to the constructor to create a map
objectMap.set, 'foo' // OK
Method 2: Use the class which has the comparison function compare()
as a key
map.setnew ExampleObject1, 'a' // OK
(If both are satisfied, method 1 takes precedence.)
If TreeMap is created without passing parameters in the above case, Error
will be thrown when the first entry is added.
✅ Do:
numberMap.set1, 'foo' // OK stringMap.set'1', 'foo' // OK dateMap.setnew Date'2019-01-01', 'foo' // OK // compareFn is definedobjectMap.setDay'2019-01-01', 'foo' // OK
🛑 Don’t:
// compareFn is not definederrMap.setDay'2019-01-01', 'foo' // throws error