Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using an Element as the key to a Hash in JavaScript

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.

like image 884
Kevin Sylvestre Avatar asked Jun 23 '13 20:06

Kevin Sylvestre


People also ask

Can we use Object as key in hashmap JavaScript?

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.

What is hash key in JavaScript?

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.

How do you hash in JavaScript?

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.

Does JavaScript have a hash 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.


1 Answers

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:

  • Firefox 6
  • Chrome 19 (disabled by default, see instructions to enable)
  • Opera 15 (disabled by default, start Opera with --js-flags=--harmony to enable it).
  • Internet Explorer 11 (confirmed to exist in leaked build)

In all other browsers, WeakMap support can be achieved by loading the WeakMap.js polyfill.

like image 104
Rob W Avatar answered Sep 20 '22 20:09

Rob W