Alex Rivera | Logout

workaround: javascript dictionary which takes objects as keys

Asked 2010-07-27T15:56:05.217
14

I read a few questions and answers about javascript dictionary implementations, but they don't meet my requirements:

  • the dictionary must be able to take objects as keys
  • the values must be accessible by the []-operator

So I came up with the idea to overwrite the valueOf-method in Object.prototype, as follows:

Object.__id__ = 0;
Object.prototype.valueOf = function() {
   if(!this.__id__)
      this.__id__ = ++Object.__id__;
    return "__id__" + this.__id__;
}
Object.prototype.toString = Object.prototype.valueOf;

//test   
var x = {p1: "5"};
var y = [6];
var z = {};
z[x] = "7";
z[y] = "8";
console.log(z[x], z[y]);

I tested this with google-chrome and it seems to work well, but I'm a bit sceptical, whether this will cause some drawbacks, since it was so easy to implement.

Considering that the valueOf method is not used for other purposes in the whole code, do you think there are any disadvantages?

Edit
Report

1 Answer

1

It is an interesting question, because I had so far assumed that any object can be used as an index (but never tried with associative arrays). I don't know enough about the inner workings of JavaScript to be sure, but I'd bet that valueOf is used somewhere else by JavaScript, even if not in your code. You might run into seemingly inexplicable problems later. At least, I'd restrict myself to a new class and leave Object alone ;) Or, you explicitly call your hashing function, calling it myHash() or whatever and calling z[x.myHash()] which adds clutter but would let me, personally, sleep better ;) I can't resist thinking there's a more JavaScript-aware solution to this, so consider all of these ugly workarounds ;)

answered 2010-07-27T16:07:16.977

Your Answer