I want to create a hash with DOM elements as keys. This is illustrated by the following code:
var hash = {};
var set = function(element, value) { hash[element] = value; };
var get = function(element) { return hash[element]; };
set(document.getElementById('foo'), 'bar');
get(document.getElementById('foo')); // returns 'bar'
How can I ensure that hash maps to a unique value for each Element
?
Note that I can't use the raw ID string as key, because any arbitrary Element
may be passed in, including those without a id.
JavaScript Objects: Similar but Different The key in a hashmap can be any datatype, this includes arrays and objects. Meanwhile, objects can only use integers, strings, and symbols as their keys. Hashmaps are organized as linked lists, so the order of its elements is maintained, which allows the hashmap to be iterable.
A hash function is a method or function that takes an item's key as an input, assigns a specific index to that key and returns the index whenever the key is looked up. This operation usually returns the same hash for a given key. A good hash function should be efficient to compute and uniformly distribute keys.
You can implement a Hash Table in JavaScript in three steps: Create a HashTable class with table and size initial properties. Add a hash() function to transform keys into indices. Add the set() and get() methods for adding and retrieving key/value pairs from the table.
In JavaScript, a “hash table” is a data structure that can be utilized to map keys to their specified values. It is also known as a “hash map“. Hash tables efficiently perform the insertion and deletion operation for a key-value pair and search the value of a key within a hash table.
In JavaScript until ES 6, only strings can be used as a key. If you want to use DOM elements, either use two linked lists, or the WeakMap
object. A bonus of the latter method is that it does not cause memory leaks.
Applied to your example:
var hash = new WeakMap();
hash.set(document.getElementById('foo'), 'bar');
hash.get(document.getElementById('foo')); // returns 'bar'
As of writing, WeakMap
is only supported by the following browsers:
--js-flags=--harmony
to enable it).In all other browsers, WeakMap support can be achieved by loading the WeakMap.js polyfill.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With