Simple Javascript Map Implementation
One of the downsides to javascript (at least in my opinion) has been it’s lack of more intelligent collection classes, such as the Map. Javascript’s array and object constructs are very flexible and useful in their own right, but sometimes you just need a way to map one object (as a key) to some arbitrary value, and then have the possibility to look up that value later. I was playing around with some ideas for how to get a simple map to work in javascript and came up with my JsMap class. It’s a very small class, more of an exercise than anything, but maybe someone will find it useful.
This map class is very limited, as (as far as I can tell) javascript objects don’t have internal hashing methods or object ids that allow for simple identification in the context of a map. In order to make up for this, my map class generates a random ID for a passed in “key” object and then uses that random ID as the key in the internal map. The generated key is then stored in a variable __jsKey in the passed in “key” object. When the “get” method on the map is called, it looks to see if the passed in “key” object has a __jsKey variable, and if so, looks up the value associated with it in the internal map.
Here is a link to the attachment page containing the javascript file, which I’ll update with changes as they’re made: [JsMap].
Here’s a simple HTML test of the map class: [JsMap Test/Example usage file]
This entry was posted on Monday, May 11th, 2009 at 2:59 pm and is filed under 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.

