HashMap Class for JavaScript
npm install hashmapHashMap class that works both on __Node.js__ and the __browser__.
Date's, RegExp's, DOM Elements, anything! (even null and undefined)
new HashMap() creates an empty hashmap
new HashMap(map:HashMap) creates a hashmap with the key-value pairs of map
new HashMap(arr:Array) creates a hashmap from the 2D key-value array arr, e.g. [['key1','val1'], ['key2','val2']]
new HashMap(key:, value:, key2:, value2:, ...) creates a hashmap with several key-value pairs
get(key:) : returns the value stored for that key.
set(key:, value:) : HashMap stores a key-value pair
multi(key:, value:, key2:, value2:, ...) : HashMap stores several key-value pairs
copy(other:HashMap) : HashMap copies all key-value pairs from other to this instance
has(key:*) : Boolean returns whether a key is set on the hashmap
search(value:) : returns key under which given value is stored (null if not found)
delete(key:*) : HashMap deletes a key-value pair by key
remove(key:) : HashMap Alias for delete(key:) (deprecated)
type(key:*) : String returns the data type of the provided key (used internally)
keys() : Array<*> returns an array with all the registered keys
values() : Array<*> returns an array with all the values
entries() : Array<[,]> returns an array with [key,value] pairs
size : Number the amount of key-value pairs
count() : Number returns the amount of key-value pairs (deprecated)
clear() : HashMap deletes all the key-value pairs on the hashmap
clone() : HashMap creates a new hashmap with all the key-value pairs of the original
hash(key:*) : String returns the stringified version of a key (used internally)
forEach(function(value, key)) : HashMap iterates the pairs and calls the function for each one
js
var map = new HashMap();
`
If you're using this within Node, you first need to import the class
`js
var HashMap = require('hashmap');
`
$3
`js
map.set("some_key", "some value");
map.get("some_key"); // --> "some value"
`
$3
`js
var map = new HashMap();
map.set("key1", "val1");
map.set("key2", "val2");
map.size; // -> 2
`
$3
`js
map.set("some_key", "some value");
map.delete("some_key");
map.get("some_key"); // --> undefined
`
$3
`js
map.set("1", "string one");
map.set(1, "number one");
map.get("1"); // --> "string one"
`
A regular Object used as a map would yield "number one"
$3
`js
var key = {};
var key2 = {};
map.set(key, 123);
map.set(key2, 321);
map.get(key); // --> 123
`
A regular Object used as a map would yield 321
$3
`js
map.set(1, "test 1");
map.set(2, "test 2");
map.set(3, "test 3");
map.forEach(function(value, key) {
console.log(key + " : " + value);
});
// ES6 Iterators version
for (const pair of map) {
console.log(${pair.key} : ${pair.value})
}
`
$3
`js
map
.set(1, "test 1")
.set(2, "test 2")
.set(3, "test 3")
.forEach(function(value, key) {
console.log(key + " : " + value);
});
``