JSFiddle - React, Tailwind, and code Playground
by zazagalaxy
HTML
<h1>Hash Compression</h1>
<h2>Assignment 9</h2>
<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>
CSS
#click {
background-color: maroon;
color: aquamarine;
margin-top: 10px;
margin-bottom: 10px;
width: 12em;
}
JavaScript
function HashTable() {
this.phrase_storage = [];
}
function Word(_word, _indexes) {
this.word = _word; // stores word
this.indexes = _indexes;
}
Word.prototype.asString = function() {
return this.word + ": " + this.indexes;
}
HashTable.prototype.new_phrase = function(phrase) {
var bin_hash = {
words: [],
found_indexes: []
}
var array_to_check_if_exist = [];
this.phrase_storage = []; //reset
for (var i = 0; i < phrase.split(' ').length; i++) {
bin_hash.words.push(phrase.split(' ')[i]);
}
//Get indexes for all words
for (let i = 0; i < bin_hash.words.length; i++) {
getAllIndexes(bin_hash.words, bin_hash.words[i]);
function getAllIndexes(array, value) {
let indexes = [];
for (let i = 0; i < array.length; i++) {
if (array[i] === value) {
indexes.push(i);
}
}
bin_hash.found_indexes.push(indexes); //adds the indexes to index hash
}
}
for (let i = 0; i < bin_hash.words.length; i++) { //pushes to phrase storage if it is not a duplicated
if (array_to_check_if_exist.indexOf(bin_hash.words[i]) == -1) {
array_to_check_if_exist.push(bin_hash.words[i]); //looks for duplication
//for all words, and store found indexes
this.phrase_storage.push(new Word(phrase.split(' ')[i], bin_hash.found_indexes[i].join(" ")));
}
}
}
HashTable.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>');
}
var hashTable = new HashTable(); // Global
document.getElementById("click").onclick = function() {
var phrase = 0;//reset when phrase clicked
phrase = document.getElementById('phrase').value;
hashTable.new_phrase(phrase);
hashTable.output();
}