Search code examples
javascripthashmapassociative-arrayobject-literal

Making an associative array in Javascript that has custom get/put operations


I need to make a Javascript object that would behave as an associative array, but with some functions that are called before getting and setting properties.

For example, the task may be like this: we should make an object, that would contain a squared value of a key, like this:

obj.two should be equal to 4, 
obj.four should be equal to 16, 
obj['twenty one'] should be equal to 441.

This is an example. Actually I need to make setting operation overridden too. The getting and setting operations would go to the database, and they not necceserily would take strings as keys, but any types of objects, from which it would create a DB query.

How would I do that a) with as less thirdparty libraries as possible and b) to make it work on as much platforms as possible?

I am new to JS, I've found that JS has no associative arrays, relying on the ability to define objects on the fly with arbitrary properties. I googled and had an idea to use or even override lookupgetter (and setter), where define a new getter/setter on the fly, but I coundn't find if the interpreter would use this method every time it encounters new key. Anyway, it looks like I wouldn't be able to use anything except strings or maybe numbers as keys.

In Java, I would just implement java.util.Map.

Please help me, how would I do the same in Javascript?

edit

I think I will get what I want if I manage to override [[Get]] and [[Put]] methods mentioned here http://interglacial.com/javascript_spec/a-8.html#a-8.6.2.1


Solution

  • I decided that the most correct way to implement this is to use Harmony:Proxies. It isn't working on all platforms, but it lets implement this in the most seamless way; and it may be supported in more platforms in the future.

    This page contains an example that I used as a template to do what I want:

    http://wiki.ecmascript.org/doku.php?id=harmony:proxies