Hash tables provide a way of efficient addition of new entries and the time spent
searching for a specified key is independent of the number of items stored, which is
O(1). Before explaining how to create a hash table in JavaScript, let’s begin with a
quick background about the associative arrays in JavaScript.
associative array (hash) is an abstract data type composed of a collection of keys
and a collection of values, where each key is associated with one value. In
JavaScript, all objects are associative arrays. You can reach the object properties as follows:
document.forms['Form1']
or
document.forms.Form1
JavaScript objects do not provide a length property like Array object but you can
iterate through the object properties using the following construct:
for (var prop in object)
For example, UltimateEditor component provides an associative array called
UltimateEditors in the client-side API. Each UltimateEditor client-side object is
defined as the property of UltimateEditors associative array. If you have multiple
UltimateEditor components in your page, the following JavaScript code will iterate
through all your UltimateEditor objects and display their HTML contents:
for (var ueObj in UltimateEditors)
{
alert(ueObj.GetEditorHTML());
}
We can now create our HashTable object using the associative array functionality.
Our HashTable object will have two properties: hashArr property that stores
key/value pairs and length property that keeps track of the number of items in the
hash table. It will provide four methods: get method to retrieve the value for a given key, put method to add a key/value pair to the hash table, remove method to
remove a key/value pair from the hash table and has method to return whether
given key value exists in the hash table.
function HashTable()
{
this.hashArr = new Array();
this.length = 0;
}
HashTable.prototype.get = function(key)
{
return this.hashArr[key];
};
HashTable.prototype.put = function(key, value)
{
if (typeof(this.hashArr[key]) == 'undefined')
{
this.length++;
}
this.hashArr[key] = value;
};
HashTable.prototype.remove = function(key)
{
if (typeof(this.hashArr[key]) != 'undefined')
{
this.length--;
var value = this.hashArr[key];
delete this.hashArr[key];
return value;
}
};
HashTable.prototype.has = function(key)
{
return (typeof(this.hashArr[key]) != 'undefined');
};
Now let’s create a sample hash table for an efficient phone lookup:
var phoneLookup = new HashTable();
phoneLookup.put('Jane', '111-222-3333');
phoneLookup.put('John', '444-555-6666');
alert(phoneLookup.get('Jane'));
0 comments:
Post a Comment