I write a program to find the longest word made of other words that is also present in array.
sort_arr.forEach(word => {
if (isLargest(word, word)) {
console.log(word);
}
});
function isLargest(initialWord, word) {
let first_half = 0;
let second_half = 0;
let start = 0;
let end = 0;
for (let i = 0; i < word.length; i++) {
end++;
first_half = word.substring(start, end);
for (let j = 0; j < sort_arr.length; j++) {
if (first_half === sort_arr[j]) {
second_half = word.substring(end, word.length);
if(second_half === ''){
return word !== initialWord;
}
else{
return isLargest(initialWord, second_half);
}
}
}
}
}
But there is a problem when array words contain
[ 'catxdogcatsrat',
'catsdogcats',
'dogcatsdog',
'cats',
'cat',
'dog',
'rat' ]
It gives output null
But the result should comes catsdogcats
I know the problem is occuring when in catsdogcats, prefix is cat and suffix is sdogcats. But it is not checking for prefix cats and suffix dogcats.
Can please some one suggest me some ways to do this without using ties.