JSFiddle - React, Tailwind, and code Playground
HTML
<input type="file" accept="text/*" id="file"/>
<p id="demo"/>
JavaScript
function readFile(event) { //read text file using Promise for asynchronous behavior
var file = event.target.files[0];
if (file) {
new Promise(function(resolve, reject) {
var reader = new FileReader();
reader.onload = function (evt) {
resolve(evt.target.result);
};
reader.readAsText(file);
reader.onerror = reject;
})
.then(findLongestConcat)
.catch(function(err) { //catch and log error invoking function
console.log(err)
});
}
}
document.getElementById('file').addEventListener('change', readFile, false);
function findLongestConcat(data) {
var list = data.split("\n");
var concatCounter = 0;
var longestWords = [];
var sLongestWords = [];
var currentWord = "";
var concatWords = [];
var longestLength = 0;
var sLongestLength = 0;
var wordsList = list.sort(function(a, b) {
return a.length - b.length; //sort words by length ascending
});
var wordDict = list.reduce(function(words, value, index) { //hash table from text file data
words[value] = true;
return words;
},{});
var isConcat = function(word) {
for (var i = word.length; i > -1; i--){
var prefix = word.slice(0,i);
var suffix = word.slice(i, word.length);
if (wordDict[prefix] === true){ //????? THIS IS ALWAYS FALSE EVEN WHEN THE KEY'S VALUE IS TRUE!!!
if (suffix.length === 0) {
return true; //all suffix are prefixes. word is concatenated.
}
return isConcat(suffix); //continue breaking remaining suffix into prefix if possible
}
}
return false;
};
while (wordsList.length !== 0) { //find out if word is concatenated
var currentWord = wordsList.pop();
wordDict[currentWord] = false;
if (isConcat(currentWord)) {
concatCounter += 1; //count total number of concatenated words
concatWords.push(currentWord);
}
}
longestLength =...