I've implemented a method to solve the following problem:
Given a
dictionaryand atextstring, find all words from thedictionarythat are present in thetext.One important point is that if the string is in double quotes, I should treat it a "single" value. If no matches found, the method should return 0.
So for this input:
const text = `Hi. I am a developer. A "Hello world" program was my first code.`;
const dictionary = "hi developer world";
I should get this:
hi
developer
hello
world
This is my current solution:
const fn = (text, dictionary) => {
const knownWords = dictionary.toLowerCase().split(' ');
const words = text.toLowerCase().match(/\w+|"[^"]+"/gi);
const result = words.reduce((acc, word) => {
if (word[0] == '"') {
const wordsNoQuotes = word.replace(/"/g, "").split(' ');
const shouldInclude = wordsNoQuotes.find(word => knownWords.includes(word));
if (shouldInclude) {
return acc.concat(wordsNoQuotes);
}
} else if (knownWords.includes(word)) {
acc.push(word)
}
return acc;
}, []);
return result.length === 0 ? 0 : [...new Set(result)].join('\n');
}
It works ok, but I would like to get some performance related improvements. I am happy to change the code (i.e using indexOf over includes) and so on. Any suggestions are welcome! Thanks.