Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript HashTable use Object key

I want to create a hash table with Object keys that are not converted into String.

Some thing like this:

var object1 = new Object(); var object2 = new Object();  var myHash = new HashTable();  myHash.put(object1, "value1"); myHash.put(object2, "value2");  alert(myHash.get(object1), myHash.get(object2)); // I wish that it will print value1 value2 

EDIT: See my answer for full solution

like image 915
Ilya Gazman Avatar asked Jun 05 '12 05:06

Ilya Gazman


People also ask

Can you use object as key in JavaScript?

Can you use objects as Object keys in JavaScript? # The short answer is "no". All JavaScript object keys are strings.

Can we use object as key in Hashmap JavaScript?

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.

Are JavaScript objects hash tables?

A JavaScript Object is an example of a Hash Table because data is represented a key/value pairs. A hashing function can be used to map the key to an index by taking an input of any size and returning a hash code identifier of a fixed size.


1 Answers

Here is a simple Map implementation that will work with any type of key, including object references, and it will not mutate the key in any way:

function Map() {     var keys = [], values = [];      return {         put: function (key, value) {             var index = keys.indexOf(key);             if(index == -1) {                 keys.push(key);                 values.push(value);             }             else {                 values[index] = value;             }         },         get: function (key) {             return values[keys.indexOf(key)];         }     }; } 

While this yields the same functionality as a hash table, it's not actually implemented using a hash function since it iterates over arrays and has a worst case performance of O(n). However, for the vast majority of sensible use cases this shouldn't be a problem at all. The indexOf function is implemented by the JavaScript engine and is highly optimized.

like image 70
Peter Avatar answered Sep 22 '22 12:09

Peter