JavaScript Map class

Java like Map class for JavaScript, a wrapper arround JavaScript’s native key value hash tree storage inside objects.

If you are familiar with Java Map this shouldn’t be news to you. The idea is this: enable the key value storage with some additional functionality, speed up iteration, and harvest the speed of native hash table key value storage.
When I say speed up iteration, I really mean it would be really neat to have getFirst and getLast property of an object, or a way to quickly get the list of the keys, or to know the number of properties at any time. To do that we need to keep an always updated array of keys, an object to hold keys and values and a length property that has the same value as the length of the array that holds keys. Keys are suposed to be small so holding a list of them wouldnt take up much of memory, but making a reverse map, that is reversely mapping keys by values would make a lot of confusion.
We have to remember that objects have unordered properties so the order of the properties will be defined in the array that keeps keys (property names), cause it is an ordered data structure.

The concept usage should be something like this:

var map = new Map();
var map1 = new Map({a:1, b:2});

alert(map.length); //0
alert(map1.length); //2

map.put(‘foo’: 1);
alert(map.length); //1
alert(map.keys()); //[‘foo’];
alert(map1.keys());//[‘a’,’b’];
map1.remove(‘a’);
alert(map1.get(‘b’)); //2
alert(map1.keys());//[‘b’];
map1.incorporate({c:3,d:4,e:5});
alert(map1.keys()); //[‘b’,’c’,’d’,’e’];
alert(map1.lenght); //4
alert(map1.getFirst()); // 2
alert(map1.getLast()); // 5
map1.put(‘b’,15)
alert(map1.getById(0)); // 15
alert(map.equals(map1)); //false
map1.clear();
map1.put(‘foo’:1);
alert(map.equals(map1)); //true

The following code enables the above described functiality. Helper functions are described in prevous posts, so for their complete understanding please refer to the older posts. Note that put and remove time is obviously slower than a regular native hash table just because of updating the array of keys.

* There was a bug in remove, made due to refactoring without thinking to much, that caused Map to get empty. It is fixed now.

I really hope you found this solution useful, if nothing, just as a simple lesson of map data structure. If you spot any bugs, or space for improvement, please comment below. The sole iteration of this data structure is left to Iterator class, that will be described in some future post.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: