Javascript HashTable use Object key -


i want create hash table gets object key without converting string.

some thing this:

var object1 = new object(); var object2 = new object();  var myhash = new hashtable();  myhash.put(object1, "value1"); myhash.put(object2, "value2");  alert(myhash.get(object1), myhash.get(object2)); // wish print value1 value2 

edit: see my answer full solution

here proposal:

function hashtable() {     this.hashes = {}; }  hashtable.prototype = {     constructor: hashtable,      put: function( key, value ) {         this.hashes[ json.stringify( key ) ] = value;     },      get: function( key ) {         return this.hashes[ json.stringify( key ) ];     } }; 

the api shown in question.

you can't play reference in js (so 2 empty objects same hashtable), because have no way it. see answer more details: how javascript object references or reference count?

jsfiddle demo: http://jsfiddle.net/hkz3e/

however, unique side of things, play original objects, in way:

function hashtable() {     this.hashes = {},     this.id = 0; }  hashtable.prototype = {     constructor: hashtable,      put: function( obj, value ) {         obj.id = this.id;         this.hashes[ this.id ] = value;         this.id++;     },      get: function( obj ) {         return this.hashes[ obj.id ];     } }; 

jsfiddle demo: http://jsfiddle.net/hkz3e/2/

this means objects need have property named id won't use elsewhere. if want have property non-enumerable, suggest take @ defineproperty (it's not cross-browser however, es5-shim, doesn't work in ie7).

it means limited on number of items can store in hashtable. limited 253, is.

and now, "it's not going work anywhere" solution: use es6 weakmaps. done purpose: having objects keys. suggest read mdn more information: https://developer.mozilla.org/en/javascript/reference/global_objects/weakmap

it differs api though (it's set , not put):

var mymap = new weakmap(),     object1 = {},     object2 = {};  mymap.set( object1, 'value1' ); mymap.set( object2, 'value2' );  console.log( mymap.get( object1 ) ); // "value1" console.log( mymap.get( object2 ) ); // "value2" 

jsfiddle demo weakmap shim: http://jsfiddle.net/ralt/hkz3e/9/

however, weakmaps implemented in ff , chrome (only if enable "experimental javascript features" flag in chrome however). there shims available, one: https://gist.github.com/1269991. use @ own risk.

you can use maps, may more suit needs, since need store primitive values (strings) keys. doc, shim.


Comments

Popular posts from this blog

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -

php - Controller/JToolBar not working in Joomla 2.5 -