I have written a function which counts how many unique words are included in a given text.
The source-code:
const computeCountUniqueWords = (strToExamine) => {
let parts = strToExamine.split(" ");
let validWords = parts.filter((word) => {
return /^\w/.test(word);
});
let uniqueWords = new Set(validWords);
return uniqueWords.size;
}
let text1 = "Lorem ipsum dolor sit amet consectetuer adipiscing elit aenean commodo ligula eget dolor.";
let text2 = "Etiam ultricies nisi vel augue. Curabitur ullamcorper";
console.log(`Text 1 has ${computeCountUniqueWords(text1)} words`);
console.log(`Text 2 has ${computeCountUniqueWords(text2)} words.`);
I think it has become quite neat and short.
Nevertheless: Is there a better way to solve the described task?
Moveover: Is my checking with the regular expression sufficient? Or should it be enhanced?
Looking forward to reading your answers.