JSFiddle - React, Tailwind, and code Playground
HTML
<p id="demo"/>
<!-- <input type="file" accept="text/*" id="file"/> -->
JavaScript
//document.getElementById('file').addEventListener('change', readFile, false);
var data = "cat cats catsdogcats dog dogcatsdog hippopotamuses rat ratcatdogcat catratdograt dogcatscats";
function findLongestWord(data) {
var list = data.split(' ');
var prefixes = {};
var prefixMatch = [];
var longestWords = [];
var sLongestWords = [];
var sLongestLength = 0;
var longestLength = 0;
var compoundWordCounter = 0;
// adds word as a prefix
var addPrefix = function (word) {
var i = 0;
var char;
var current = prefixes;
while (char = word[i++]) {
if (!current[char]) {
current[char] = {};
}
current = current[char];
}
current.word = true;
};
// Finds the longest prefix we can make using the word.
var findPrefixes = function (word) {
var prefix = '';
var found = [];
var i = 0;
var char;
var current = prefixes;
while (char = word[i++]) {
if (!current[char]) {
break;
}
// Move to the next character and add to the prefix.
current = current[char];
prefix += char;
if (current.word){ //this is the problem
found.push(prefix);
}
}
return found;
};
//for each word in list, add to prefix
list.forEach(function (word) {
var prefix;
// If we can find a closest possible word, it may be possible to create a
// compound word - but we won't be able to check until we reach the end.
if ((prefix = findPrefixes(word)) && prefix.length) {
prefixMatch.push([ word, prefix ]);
}
// Insert the word into the prefix tree.
addPrefix(word);
});
prefixMatch.forEach(function (possible) {
var word = possible[0];
var prefixes = possible[1];
//var found = false;
var findCompoundWord = function (suffix) {
// Find all future prefixes and continue search.
if (suffix) {
return findPrefixes(suffix).forEach(function (prefix) {
//!found &&...