Assignment 9 - Hashing

by aren_anderson

HTML

<h1>
Hashing
</h1>

<h4>
Please enter a value to hash: <input type="textbox" id="tbPhrase" />
</h4>

<input type="button" id="btnParse"  value="Parse Phrase" onClick="parsePhrase();"/>

<div id="output">
</div>

JavaScript

//global variables for hashtable and LL
var list = new LinkedList();
var hashTable = new HashTable();

function LinkedList() {
	this.length = 0;
  this.head = null;
  this.length = null
}

function Node(){
	this.next = null;
  this.prev= null;
  this.content = null;
}

//function to add content to Node
LinkedList.prototype.add = function(content){
	var node = new Node(); 
  node.content = content;
  
  if (this.head == null){
  	this.head = node; 
    this.length = 1;
    return node;
  }

  if (this.tail == null){
  	this.tail = node;
    this.tail.prev = this.head;
    this.head.next = this.tail;
    this.length++;
    return node;
  }
  
  this.tail.next = node;
  node.prev = this.tail;
  this.tail = node;
  this.length++;
  return node;
}

//function to parse text into hashTable
function parsePhrase(){ 
  document.getElementById("output").innerHTML = "";
	var phrase = document.getElementById("tbPhrase").value;
  var phraseAsStringArray = phrase.split(" ");
  var len = phraseAsStringArray.length;
  
  for (var i = 0; i < len; i++){
  	hashTable.addWord(phraseAsStringArray[i], i+1);
  }
}

function HashTable(){
	this.bins = list;
  this.addWord = function(word, index){
  	var out = "";
    var counter = 0;
    var head = this.bins.head;
    var length = this.bins.length;
    
    for (var i = 0; i < length; i++){
    	if (head.content.word == word){
      	head.content.index.push(index);
        counter++;
      }
      head = head.next;
    }
    if (counter == 0){
    	w = new Word(word);
      w.index.push(index);
      list.add(w);
    }
    head = this.bins.head;
    
    for (var k = 0; k < this.bins.length;
    k++){
    	out += head.content.word + ": " + head.content.index + "<br />";
      head = head.next;
    }
    document.getElementById("output").innerHTML = out;
  }
}

function Word(word){
	this.word = word;
  this.index = [];
}