Re: JavaScript Hashtable Implementation
This is in response to my previous post re
JavaScript Hashtable Implementation. I modified my code to be able to remove elements, as well as get an enumeration of the elements in cases wherein the keys are strings rather than integers.
Here are the new members of the Hashtable object:
Methods:remove(string keyName) - Remove an element by key name
getAt(int index) - Get the value at the specified index
getEnum[int index] - Get the
key name at the specified index
Properties:count - Get the number of elements of the Hashtable object
location - (
deprecated)
So, here's the new code:
// create an instance of the hashtable object
function Hashtable(){
this.hash = new Array();
this.keys = new Array();
this.getEnum = new Array();
this.count = 0;
}
Hashtable.prototype.hash = null;
Hashtable.prototype.keys = null;
Hashtable.prototype.count = null;
Hashtable.prototype.getEnum = null;
// get the value at the specified index
Hashtable.prototype.getAt = function (index) {
return this.hash[this.getEnum[index]];
}
// get the corresponding value
Hashtable.prototype.get = function (key) {
return this.hash[key];
}
Hashtable.prototype.remove = function (key) {
for (var i = this.keys.length - 1; i >= 0; i--) {
if (this.keys
== key) {
this.keys.splice(i, 1);
this.getEnum.splice(i, 1);
this.hash[key] = null;
this.count = this.keys.length;
}
}
}
// create an entry in the hashtable
Hashtable.prototype.put = function (key, value) {
if (value == null)
return null;
// create a new entry
if (this.hash[key] == null) {
this.keys[this.keys.length] = key;
this.count = this.keys.length;
this.getEnum[this.count - 1]= key;
}
// set the value
this.hash[key] = value;
}
Read the complete post at http://alexrazon.blogspot.com/2007/02/re-javascript-hashtable-implementation.html