Module 8
by leiperte
HTML
<h1>Module 8</h1>
<form id="form">
<div id="my-div">
Enter value.<br>
<input type="text" id="phrase"><br>
<input type="button" value="Enter" id="click">
</div>
</form>
<div id="output"></div>https://jsfiddle.net/jtlindsey/pj2gxwvh/#
CSS
#click {
background-color: blue;
color: white;
margin-top: 8px;
margin-bottom: 8px;
width: 10em;
}
JavaScript
function Bin () {
this.phrase_storage = [];// place to store phrase words
}
function Word(word, indexes) {
this.word = word; this.indexes = indexes;
}
Word.prototype.asString = function () {
return this.word + ": " + this.indexes;
};
Bin.prototype.new_phrase = function (phrase) {
var bin_hash = {words: [], found_indexes: []}, array_to_check_if_exist = [];
this.phrase_storage = []//reset
//split phrase into words and store in bin_hash.words
for (var i=0; i<phrase.split(' ').length; i++) {
bin_hash.words.push(phrase.split(' ')[i]);
}
//get indexes for all words
for (var i=0; i<bin_hash.words.length; i++) {
getAllIndexes(bin_hash.words, bin_hash.words[i])
function getAllIndexes(array, value) {
var indexes = [];
for(var i=0; i<array.length; i++) {
if (array[i] === value) {
indexes.push(i+1);//plus one since in professors example he counted from 1 not 0
}
}
bin_hash.found_indexes.push(indexes);//add indexes to index hash
}
}
for (var i=0; i<bin_hash.words.length; i++) {//will push to phrase storate if not duplicate
if (array_to_check_if_exist.indexOf(bin_hash.words[i]) == -1) {
array_to_check_if_exist.push(bin_hash.words[i]);//push to array to monitor for duplicates
//for all words, store found indexes
this.phrase_storage.push(new Word(phrase.split(' ')[i], bin_hash.found_indexes[i].join(" ")));
}
}
}
Bin.prototype.output = function () {
var output_array = [];
for (var i=0; i<this.phrase_storage.length; i++) {
output_array[i] = this.phrase_storage[i].asString();
}
return document.getElementById("output").innerHTML = output_array.join('<br>');
}
test = new Bin();
document.getElementById("click").onclick = function() {
new_phrase = 0; //reset when phrase clicked
new_phrase = document.getElementById("phrase").value;
test.new_phrase(new_phrase);
//test.new_phrase(new_phrase.toLowerCase());//if want downcase
...