In JavaScript, all Objects act a bit like hashmaps. However, the keys to these hashmaps must be strings. If they\'re not, they\'re converted with toString()
. Tha
Here's a quick proof-of-concept...
I've hardly tested it at all, and I'm certain that there will be corner-cases that it can't deal with.
Performance will be hideously inefficient because the __createHash
function needs to recurse through the members of any objects and then sort them, in order to generate a "hash" that meets your requirements.
HashMap = function() {
this.get = function(key) {
var hash = this.__createHash(key);
return this.__map[hash];
};
this.set = function(key, value) {
var hash = this.__createHash(key);
this.__map[hash] = value;
};
this.__createHash = function(key) {
switch (typeof key) {
case 'function':
return 'function';
case 'undefined':
return 'undefined';
case 'string':
return '"' + key.replace('"', '""') + '"';
case 'object':
if (!key) {
return 'null';
}
switch (Object.prototype.toString.apply(key)) {
case '[object Array]':
var elements = [];
for (var i = 0; i < key.length; i++) {
elements.push(this.__createHash(key[i]));
}
return '[' + elements.join(',') + ']';
case '[object Date]':
return '#' + key.getUTCFullYear().toString()
+ (key.getUTCMonth() + 1).toString()
+ key.getUTCDate().toString()
+ key.getUTCHours().toString()
+ key.getUTCMinutes().toString()
+ key.getUTCSeconds().toString() + '#';
default:
var members = [];
for (var m in key) {
members.push(m + '=' + this.__createHash(key[m]));
}
members.sort();
return '{' + members.join(',') + '}';
}
default:
return key.toString();
}
};
this.__map = {};
}