Hashing has lots of benefits for storing data. We achieve hashing in various languages but doing it througn Javascript was something very special. While the basic purpose of using a Hash Table is to store a key value pair, but there are also other ways to use it. I used it for checking duplicate values. Below is the code for Hash Tables in Javascript.
Code for creating a Hash Table:
//Initializes the Hash Table
function HashTable(){ this.hashArr = new Array(); this.length = 0;}
//Get Function to read the contents
HashTable.prototype.get = function(key) { return this.hashArr[key];};
//Put function for storing key value
HashTable.prototype.put = function(key, value) { if (typeof(this.hashArr[key]) == 'undefined') { this.length++; } this.hashArr[key] = value;};
For Checking Duplicate values:
Store the element to be checked as key. If Duplicate it will not get inserted and the length of Hash Table remains same. Compare this value with a counter. If counter is greater than length it is a duplicate.
Thursday, January 22, 2009
Subscribe to:
Posts (Atom)