Javascript Map – Version 0.2
After trying to use my previous map implementation in a Firefox extension I’ve been working on I realized that you can’t add random attributes to some objects you deal with in that world. This made my previous approach unworkable. After doing some more searching, I found an approach that seems to work well so far.
The basic idea is that we want to be able to generate an identifier for a random object consistently, then we can associate this identifier with a value. The limitation is that the identifier needs to be a string (limitation of Javascript’s internal associative array/object construct), and that native javascript objects don’t have an internal mechanism for generating an ID (unlike Java’s Object class, which provides a hashCode() method).
The process to solve this problem has two steps in my current implementation:
- Store the ‘key’ object in an array
- Use the ‘key’ object’s array index as the key value for the association
This way, I can tell if a passed in ‘key’ object has a value in my map by seeing if it’s in my internal array. If it’s in there, I can look up it’s index’s value in my associative array (or anonymous object). If I’m adding a new key/value pair, I insert the key object into my internal array and then use it’s index as the ‘key’ for my associative array. Removing a key/value pair from the map involves the following steps:
- Look up the index of the key object in my internal array
- Remove the value that corresponds to the index from the associative array/anonymous object
- Remove the key object from the internal array
Here’s an example of the code that inserts a key/value pair into the map, this is a snip from the code, which is more object-oriented:
// Internal holders var _internalMap = {}; var _internalArray = new Array(); /* * Private function for getting the key for an object */ function getKey(obj) { var key = _internalArray.indexOf(obj); if(key == -1) { _internalArray.push(obj); key = _internalArray.indexOf(obj); } // "Keys" will be of the form "OR.x" where 'x' is the index in the array return "OR." + key; }; /* * Internal put method */ put = function(key, value) { var objKey = getKey(key); _internalMap[objKey] = value; };
The full implementation has get, remove, and size methods as well, and is built as a class, but this kind of shows the mechanism behind it all. One thing to note is that this implementation relies on Javascript 1.6 (or higher) as the ‘indexOf()’ array method was introduced in Javascript 1.6
I’ve attached the new version (version 0.2), you can find it here: JsMap Version 0.2
This entry was posted on Wednesday, May 20th, 2009 at 12:41 pm and is filed under Learning, Programming Problems. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

