Assignment 9
by austinmillett
HTML
<!-- Heading 1 -->
<h2> Austin Millett </h2>
<!-- Heading 2 -->
<h3> Assignment 9 - Hash Compressions </h3>
<!-- Form - Text area -->
<form id = "form"> Enter Phrase.
<br>
<textarea id = "phrase" rows = "5" cols = "40"> </textarea>
<br>
<input type = "button" value = "Hash Phrase" id = "HASH" onClick = "hashPhrase();">
</form>
<!-- Div for output -->
<div id = "output"></div>
CSS
/* Design for "Enter Number" button */
#HASH {
background-color: black;
border: 2px solid;
color: white;
padding: 4px 8px;
text-align: center;
font-size: 15px;
}
JavaScript
//Create the hash table
var htable = new HashTable();
// On clicking hash phrase button it call hashPhrase function()
function hashPhrase() {
htable.bins = [];
var ph = document.getElementById('phrase').value;
var ph_string_array = ph.split(' ');
var lenn = ph_string_array.length;
for (var i = 1; i < lenn; i++) {
htable.Word_add(ph_string_array[i], i );
}
print();
}
function HashTable() {
this.bins = [];
//function for adding word
this.Word_add = function(phrase_word, location) {
//If word already exist
if (this.Word_exist(phrase_word) == true) {
this.add_exist_word(phrase_word, location);
} else {
//If word is new
this.add_new_word(phrase_word, location); //add new word
}
return phrase_word;
};
//function checking the word exist
this.Word_exist = function(phrase_word) {
var x = false;
for (var i=0; i<this.bins.length; i++) {
var Word_hashed = this.bins[i].split(":");
if (Word_hashed[0] == phrase_word) {
x=true;
}
}
return x;
};
//function adding new word
this.add_new_word = function(phrase_word, location) {
var element = phrase_word + ": " + location;
this.bins.push(element);
return phrase_word;
};
this.add_exist_word = function(phrase_word, location) {
for (var i=0; i<this.bins.length; i++) {
var Word_hashed = this.bins[i].split(":");
var existing_value = this.bins[i];
if (Word_hashed[0] == phrase_word) {
this.bins[i] = existing_value + " " + location;
}
}
return phrase_word;
};
}
//Output
function print() {
var output="";
for (var i in htable.bins) {
output = output + htable.bins[i] + "<br /><br />";
}
document.getElementById('output').innerHTML = output;
}