Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can anyone recommend a good Hashtable implementation in Javascript? [duplicate]

I need to store some statistics using JavaScript in a way like I'd do it in C#:

Dictionary<string, int> statistics;  statistics["Foo"] = 10; statistics["Goo"] = statistics["Goo"] + 1; statistics.Add("Zoo", 1); 

Is there an Hashtable or something like Dictionary<TKey, TValue> in JavaScript?
How could I store values in such a way?

like image 997
George2 Avatar asked Jul 30 '09 17:07

George2


People also ask

What are the criteria for choosing a good hash function?

Characteristics of a Good Hash Function. There are four main characteristics of a good hash function: 1) The hash value is fully determined by the data being hashed. 2) The hash function uses all the input data. 3) The hash function "uniformly" distributes the data across the entire set of possible hash values.

How are hash tables implemented 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.

How could the performance of the hash table be improved?

The simplest and most obvious improvement would be to increase the number of buckets in the hash table to something like 1.2 million -- at least assuming your hash function can generate numbers in that range (which it typically will).

Is double hashing better?

Advantages of Double hashing The advantage of Double hashing is that it is one of the best form of probing, producing a uniform distribution of records throughout a hash table. This technique does not yield any clusters. It is one of effective method for resolving collisions.


1 Answers

Use JavaScript objects as associative arrays.

Associative Array: In simple words associative arrays use Strings instead of Integer numbers as index.

Create an object with

var dictionary = {}; 

JavaScript allows you to add properties to objects by using the following syntax:

Object.yourProperty = value; 

An alternate syntax for the same is:

Object["yourProperty"] = value; 

If you can, also create key-to-value object maps with the following syntax:

var point = { x:3, y:2 };  point["x"] // returns 3 point.y // returns 2 

You can iterate through an associative array using the for..in loop construct as follows

for(var key in Object.keys(dict)){   var value = dict[key];   /* use key/value for intended purpose */ } 
like image 138
Alek Davis Avatar answered Oct 03 '22 20:10

Alek Davis