hash

by chris richarde

HTML

<form id="form">Enter Phrase.
    <br>
    <textarea id='phrase' rows='10' cols='50'>I want what I want and I know what I want</textarea>
    <br>
    <input type="button" value="Parse Phrase" id="parse" onClick='parsePhrase();'>
</form>
<div id="output"></div>

JavaScript

var hashTable = new HashTable(); // Global
function parsePhrase() {
    var phrase = document.getElementById('phrase').value;
    var phraseAsStringArray = phrase.split(' ');
    var len = phraseAsStringArray.length;
    hashTable.bins = [];
    for (var i = 0; i < len; i++) {
        //alert(phraseAsStringArray[i]);
        hashTable.addWord(phraseAsStringArray[i],i+1);
    };
	
  hashTable.print();
}

function HashTable(){
    this.bins = []; 
    this.addWord = function(word, loc) {
        if(this.hasWord(word)){
        	this.addExistingWord(word, loc);
        }
        else{
        this.addNewWord(word,loc);
        }	
       return word;    
    };
    
    this.hasWord = function(word) {
       	
        for(var i=0; i<this.bins.length; i++){
        	 var L  = word.toLowerCase();
         	 var U = word.toUpperCase();
          if(this.bins[i].word == word ||this.bins[i].word == word.toLowerCase() ||this.bins[i].word == word.toUpperCase() ){
          	return true; // couldn't get the if statement to include upper and lower case in boundaries for being the same word.actually sometimes they will disappear if they are upper and lower case copies.
        	}
        }  
    	return false;
    };
    
    this.addNewWord = function(word, loc) {
        var x = new Word(word, loc);
        this.bins.push(x);
        return word;
    };
    
    this.addExistingWord  = function(word, loc) {
       	for(var i=0; i<this.bins.length; i++){
        	if(this.bins[i].word == word){
          	this.bins[i].num.push(loc);
          }
        }
        return word;
    };

		this.print = function (){
      for(var i=0; i < this.bins.length; i++){
           var word = this.bins[i];
           document.getElementById('output').innerHTML+= word.word + ' => ' + word.num + '<br/>';
        }
        
    }

}

function Word(word, loc) {
    this.word = word; // store word
    this.num=[];
    this.num.push(loc);
    // Probably want some logic here

    }