Let's take an example with different variations of the word "themselves" like "themselves"
, "Themselves"
, or " THEMSelveS "
(notice the leading and trailing spaces), all should be considered as one count for themselves: 3
This is my code:
const { readFile, readFileSync } = require('fs');
let file = 'C:\Users\eeroj\source\repos\Nodejs\pish\pish';
function countRepeatedWords(sentence) {
let words = sentence.split(" ");
let wordMap = {};
for (let i = 0; i < words.length; i++) {
let currentWordCount = wordMap[words[i]];
let count = currentWordCount ? currentWordCount : 0;
wordMap[words[i]] = count + 1;
}
const sortedEntries = Object.entries(wordMap).sort(([a,], [b,]) => a.localeCompare(b));
const sortedWordMap = Object.fromEntries(sortedEntries);
return sortedWordMap
return wordMap;
}
words = readFileSync(file).toString();
console.log(countRepeatedWords(words));