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
Can you use objects as Object keys in JavaScript? # The short answer is "no". All JavaScript object keys are strings.
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 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.
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.
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