Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a hashmap library for JavaScript?

In JavaScript, all Objects act a bit like hashmaps. However, the keys to these hashmaps must be strings. If they're not, they're converted with toString(). That means:

var a = {foo: 1};
var b = {bar: 2};
var o = {};
o[a] = 100;
o[b];              // 100
JSON.stringify(o); // '{"[object Object]":100}'

That is, since the toString() of any plain Object is [object Object], they all address the same value.

I'd like to create a hashmap where Objects with the same properties and values address the same value, but objects with different properties or values address different values. That is:

var a = {foo: 1};
var b = {bar: 2, baz: 3};
var c = {baz: 3, bar: 2};
var hash = new Hash();
hash.set(a, 100);
hash.get(b);      // undefined
hash.set(b, 200);
hash.get(b);      // 200
hash.get(c);      // 200

My first instinct was to use JSON.stringify() to turn objects into strings, but:

var hash = {};
var b = {bar: 2, baz: 3};
var c = {baz: 3, bar: 2};
hash[JSON.stringify(b)] = 100
hash[JSON.stringify(b)] // 100
hash[JSON.stringify(c)] // undefined
JSON.stringify(b)       // '{"bar":2,"baz":3}'
JSON.stringify(c)       // '{"baz":3,"bar":2}'

That is, JSON serialization is order-dependent.

Is there a good library or technique to implement a hashmap like this?

Update:

Equivalently, is there a good hashing function such that:

hash({foo: 1, bar: 2}) == hash({bar: 2, foo: 1})
like image 841
Peeja Avatar asked Jul 22 '10 14:07

Peeja


People also ask

Does JavaScript have a hashmap?

While JavaScript doesn't have a native Hashtable class, it does have native Objects and Hashmaps(Map) that offer similar functionality when it comes to organizing key/value pairs.

Are JavaScript maps hash tables?

Note: Regular Javascript objects and the Map class are both simple key-value hash tables/associative arrays, with a few key differences: A Map object can iterate through its elements in insertion order, whereas JavaScript's Object s don't guarantee order.

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

I would recommend you the jshashtable project from Tim Down.

like image 172
Christian C. Salvadó Avatar answered Nov 04 '22 04:11

Christian C. Salvadó