Tuesday, September 25, 2007

JavaScript Hashtable based on MS AJAX

I was looking to implement a JavaScript hashtable and after find a number of near identical implementations, I decicded to modify one that I found at http://alexrazon.blogspot.com/2006/11/javascript-hashtable-implementation.html to be based on the MS Ajax Patern.

Anyways, here it is:



Mbccs.Psp.Web.Manager.Hashtable = function() {
this._hash = new Array();
this._keys = new Array();
this._getEnum = new Array();
this._count = 0;
}

Mbccs.Psp.Web.Manager.Hashtable.prototype = {
getAt : function(index) {
return this._hash[this._getEnum[index]];
},

get : function (key) {
return this._hash[key];
},

remove : function (key) {
for (var i = this._keys.length - 1; i >= 0; i--) {
if (this._keys[i] == key) {
this._keys.splice(i, 1);
this._getEnum.splice(i, 1);
this._hash[key] = null;

this._count = this._keys.length;
}
}
},

put : function (key, value) {
if (value == null)
return null;
if (this._hash[key] == null) {
this._keys[this._keys.length] = key;
this._count = this._keys.length;
this._getEnum[this._count - 1] = key;
}

this._hash[key] = value;
}
}

Mbccs.Psp.Web.Manager.Hashtable.registerClass('Mbccs.Psp.Web.Manager.Hashtable');

if(typeof(Sys) !== 'undefined')
Sys.Application.notifyScriptLoaded();

2 comments:

Anonymous said...

That's a nice first start, however it 's not a complete port of the full implementation.

I've seen a more fulsome implementation here http://www.comet.co.il/en/articles/hash/article.html

(the full implementation is actually a download off that page).

It's a slick implementation, but the way they handle enumerating is a bit suspect - it doesn't even attempt to be thread-safe.

Anonymous said...

Ok, I didn't want to be anonymous, but the comment form ain't saving in anything other than Anonymous mode.

- Jason Glover