NerdyHearn
Home
Blog

Contact
Mailing List

Software


Blog
Twitter

NerdyHearn - Blog


<< Back To All Blogs

Implementing a basic Hashtable in Javascript

Saturday, August 9th, 2008

Javascript does not have a native type that is comparable to a Hashtable. So without further comment, I present to you my implementation of a javascript hashtable:

nerdyhearn.Hashtable = function() {
this.Keys = [];
this.Values = [];
}

if (!nerdyhearn.Hashtable.prototype.add) {
nerdyhearn.Hashtable.prototype.add = function(key, value) {
this.Keys.push(key);
this.Values.push(value);
}
}

if (!nerdyhearn.Hashtable.prototype.get) {
nerdyhearn.Hashtable.prototype.get = function(key) {
for (int a=0; a if (this.Keys[a] == key) {
return(this.Values[a]);
}
}
throw new Exception("Key not found in hashtable.");
}
}

if (!nerdyhearn.Hashtable.prototype.remove) {
nerdyhearn.Hashtable.prototype.remove = function(key) {
for (int a=0; a if (this.Keys[a] == key) {
this.Keys.splice(a, 1);
this.Values.splice(a, 1);
}
}
throw new Exception("Key not found in hashtable.");
}
}

That should be pretty self-explanatory, if you have any questions, feel free to comment away.

Hashtable Tom Out.

Comments

jim said on Monday, August 11th, 2008 @ 1:53 PM

Please just use {} its more native than in any other language.

Ken Snyder said on Monday, August 11th, 2008 @ 12:30 PM

Why not use JavaScript's built in objects?

var Hashtable = function() {
this.data = {};
};
Hashtable.prototype.set = function(key, value) {
this.data[key] = value;
};
Hashtable.prototype.get = function(key) {
return this.data[key];
};
Hashtable.prototype.remove= function(key) {
delete this.data[key];
};

I suppose one advantage to using two arrays is that keys aren't limited in size. I've heard that keys can be as big as 1kb across all browsers, but I don't know.

Add A Comment

Name:


URL:


Email Address: (not public, used to send notifications on further comments)


Comments:



Enter the text above, except for the 1st and last character:


NerdyHearn - Latest tech news relating to C#, ASP.NET, SharePoint, PHP, general development, and more. SaveMySerials - Protect yourself from theft, fire, natural disasters and more by recording your serial numbers