Hash Table

by Juan Alban Franco

HTML

<html>

<body>
<input type = textbox value = "The quick brown fox jumped over the lazy dog dog dog " id = in>
<input type = button value = 'Compress Phrase' onclick = begin()>
<p id = 'out'>

</p>

</body>
</html>

JavaScript

function HashTable(size) { 
	this.buckets = Array(size);
  this.numBuckets = this.buckets.length;
  }
  
 function Node(key,value){
 	this.key = key;
  this.value = value;
  this.next = null  ;
 }
 
//function below iterates through the key and creates a unique key code -> bucket relationship. 
HashTable.prototype.hash = function(key){
/*	var count = 0;
	var total = 0;
  for (var i = 0; i<key.length; i++){
  	total += key.charCodeAt(i); //baked in function to find char code.

  }
  var bucket = total % this.numBuckets
 
  return bucket; // the bucket returned will be the index in the array that the key will be placed in
*/
	var index = 0;
  var exist = 0;
  for (var i =0 ;i < this.numBuckets;i++){
  	if (this.buckets[i] == undefined){
     index = i;
    }
    else if( this.buckets[i].key == key){
    return i;
    }
   }
   return index;

}

HashTable.prototype.insert = function (key, value){
	var index = this.hash(key);
  
  var current = new Node();
	if(!this.buckets[index]|| this.buckets == undefined){
		this.buckets[index] = new Node(key,value);
	}
	else
    current = this.buckets[index];
		while (current.next != null){
				current = current.next;
		}
				current.next = new Node(key,value)		
	}
  
  
  
HashTable.prototype.print = function (){
	var traveler = new Node();
  var string = "";
  for (var i = this.numBuckets -1 ;i >= 0; i--){
      if(this.buckets[i] == undefined){continue;}
      else{
      	traveler = this.buckets[i];
        string += this.buckets[i].key+ ' ';
         while(traveler){
        		string += traveler.value + ' ';
          	traveler = traveler.next;
        	}
         string += '<br>';
         }
      } 
document.getElementById("out").innerHTML = string;
}
  
  
function begin() {    
var array = [];
var strholder = "";
var str = document.getElementById("in").value.trim() + ' ';
var j= 0;
for (var i = 0; i<str.length;i++){
	if(str[i] != " "){
  strholder += str[i].trim();
 
  }
  else{
  array[j] = strholder;
  strholder =...