JSFiddle - React, Tailwind, and code Playground
by Erik East
HTML
<h1>Module 08</h1>
<h2>Assignment 9</h2>
<p>Enter a phrase below:</p>
<form id="form">
<textarea id='phrase' style="width: 200px; height:50px;">This isn't who it would be if it wasn't who it is</textarea>
<input type="button" value="Parse Phrase" id="parse" onClick='parsePhrase();'>
</form>
<div id="output"></div>
<p id='output1'></p>
JavaScript
function parsePhrase() {
var phrase = document.getElementById('phrase').value;
var phraseAsStringArray = phrase.split(' ');
var lenAll = phraseAsStringArray.length;
var h = new HashTable(phraseAsStringArray);
debugger;
var s = PrintHashTable(h);
document.getElementById('output1').innerHTML = s;
}
function onlyUnique(value, index, self) {
return self.indexOf(value) === index;
}
function HashTable(ar){
var uniqueWordsArray = ar.filter(onlyUnique);
var allIndices = [];
var len = uniqueWordsArray.length;
for (var i = 0; i < len; i++) {
var idx = GetAllOccurences(ar,uniqueWordsArray[i]);
allIndices.push(idx);
}
this.allWords = uniqueWordsArray;
this.allIndices = allIndices;
}
function GetAllOccurences(ar,element){
var indices = [];
var idx = ar.indexOf(element);
while (idx != -1) {
indices.push(idx+1);
idx = ar.indexOf(element, idx + 1);
}
return indices;
}
function PrintHashTable(ht){
var words = ht.allWords;
var ind = ht.allIndices;
var str = "";
var l = words.length;
for (var i = 0; i < l; i++) {
var j = ind[i];
var s = j.join(" ");
str = str + (words[i] + ": " + s + "<br>");
}
return str;
}