Javascript HashMap
Reading around i’ve discovered that Javascript associative arrays returns unpredictable results, i.e. length param is not correctly handled.
Array object should be used only with a numeric index and best way to avoid this problem is to use Object.
But, if I wanna put more objects in my object?
Of course i can do this with previous method, but i don’t like it :-P. So, i’ve written a 100% OOP class, that use Prototype and it simulate a java HashMap.
I’ve also implemented an exception handling.
A little example:
var myHM = new HashMap();
myHM.put('a', new String('This string contains A'));
myHM.put(new String('b'), new String('This string contains B'));
myHM.put('0', new String('And this string? Zero'));
window.alert(myHM.size()); // returns 3
// Replace
// Notice that you can use both String object or scalar value.
myHM.put('b', new Date());
if( myHM.get('b') instanceof Date )
window.alert('It\'s a Date');
// Remove
if( myHM.containsKey('a') && myHM.containsValue('This string contains A') )
window.alert('\'A\' object is present');
myHM.remove('a');
if( myHM.containsKey('a') || myHM.containsValue('This string contains A') )
window.alert('Ooops \'A\' is still present'); // Don't display
window.alert(myHM.size()); // returns 2
// Clear
myHM.clear();
window.alert(myHM.size()); // returns 0
I hope this is useful for you, of course I’ve attached source code.