Hash code #2
by arosado417
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;
for (var i = 0; i < len; i++) {
//alert(phraseAsStringArray[i]);
hashTable.addWord(phraseAsStringArray[i],i+1);
}
for(var word in hashTable.bins){
//console.log(word + " : " + hashTable.bins[word].indexes);
document.getElementById("output").innerHTML += word + " : " + hashTable.bins[word].indexes.join(" , ") + "<br />" ;
}
}
function HashTable(){
// Decide how to store the bins - add here
// This will contain all the Words
this.bins = Array (); // using array as example (list is better)
this.addWord = function(word, index) {
// alert('Adding ' + word + ' to Hash Table, remove this alert in your submission');
//for()
// return word;
// You will add a word to the HashTable
// If word is in table add to Word
// If not create new one
if(!this.hasWord(word)){
this.bins[word] = new Word(word);
}
this.bins[word].indexes.push(index);
return word;
}
this.hasWord = function(word) {
return this.bins[word] && this.bins[word].indexes;
};
}
function Word(word) {
this.word = word; // store word
this.indexes = []; // using array to store indexes
}
/*
Assignment
If you look at some compression techniques (such as LZW Compression https://en.wikipedia.org/wiki/Lempel%E2%80%93Ziv%E2%80%93Welch ) they make use of the concept of hashing techniques to compress files. We are going to do something similar. Consider the phrase
To be or not to be, that is the question.
Even though it does not make much sense to do this as the phrase is short. We are going to create bins for each word, and record the position of the instances of the words in the...