Assignment 9
by Kristy Bond
HTML
<form id="form">Enter Phrase.
<br/>
<textarea id="phrase" rows="5" cols="50">How much wood would a woodchuck chuck
if a woodchuck could chuck wood?
He would chuck, he would, as much as he could,
and chuck as much wood as a woodchuck would
if a woodchuck could chuck wood.</textarea>
<br/>
<input type="button" value="Parse Phrase" id="parse" onClick=parsePhrase();>
</form>
<br/>
<div id="output"></div>
JavaScript
var hashTable = new HashTable();
function parsePhrase() {
hashTable.clear();
var phrase = document.getElementById("phrase").value;
var phraseAsStringArray = phrase.split(" ");
var len = phraseAsStringArray.length;
for (var i = 0; i < len; i++) {
hashTable.addWord(phraseAsStringArray[i], i + 1);
}
document.getElementById("output").innerHTML = hashTable.print();
}
function HashTable(obj) {
this.bins = {};
this.length = 0;
for (var p in obj) {
if (obj.hasOwnProperty(p)) {
this.bins[p] = obj[p];
this.length++;
}
}
this.addWord = function(word, index) {
if (this.hasWord(word)) {
this.addExistingWord(word, index);
}
else {
this.addNewWord(word, index);
}
return word;
}
this.hasWord = function(word) {
return this.bins.hasOwnProperty(word);
}
this.addNewWord = function(word, index) {
this.bins[word] = index;
this.length++;
return word;
}
this.addExistingWord = function(word, index) {
var current = this.bins[word];
this.bins[word] = current + " " + index;
return word;
}
this.print = function() {
var str = "";
for (var w in this.bins) {
if (this.hasWord(w)) {
str = str + w + ": " + this.bins[w] + "<br/>";
}
}
return str;
}
this.clear = function() {
this.bins = {};
this.length = 0;
}
}