| |
|
|
By Uzi Refaeli [ 27/10/2005 ] Publishing Free Articles Zone articles is subject to our Publisher's Terms Of Service |
|
Very often there is a need to use a data structure that keeps parameters in a form of key-value.
Associative Array (i.e. JavaScript Array Object)is such a solution.
Although it has low memory signature and quick data fetching we cannot iterate thru the array elements using direct key-value interface.
Web applications developed for IE based browsers have the option to use the Microsoft Dictionary object.
Massive use of the object may cause high memory signature and low application performance.
This article introduces a possible solution to this problem, a solution which is deployed in real world running applications.
JavaScript Hashtable Object
The idea behind using this object is having the properties of associative Array bundled with low order computational complexity data fetching,
by adding new methods and capabilities.
Let's start by defining the class members:
Hashtable.prototype.hash = null;
Hashtable.prototype.keys = null;
Hashtable.prototype.location = null;
function Hashtable(){
this.hash = new Array();
this.keys = new Array();
this.location = 0;
}
Hashtable.prototype.get = function (key)
return this.hash[key];
}
Hashtable.prototype.put = function (key, value){
if (value == null)
return null;
if (this.hash[key] == null)
this.keys[this.keys.length] = key;
this.hash[key] = value;
}
//declare an instance
var items = new Hashtable();
//add 3 values to the hash
items.put("key1", "value1");
items.put("key2", "value2");
items.put("key3", "value3");
//just show that all works well
alert(items.get("key2"));
//start iterating the hash
//Just to be on the safe side (maybe someone has used it before?)
items.moveFirst();
while (tems.next()){ //While we have more elements
//print the key and the value
alert (items.getKey() + " = " + items.getValue());
}
About the author:
Uzi Refaeli is the CTO of Comet Information Systems which specialize with technology entrepreneurship and web development.
Article Source: http://www.Free-Articles-Zone.com