Is it possible to make it so that when dealing with a code and a text file, you don't have to specify the file path every time or share a changing location with others?
Here is my code:
const { readFile, readFileSync } = require('fs');
let file = 'C:\\Users\\eeroj\\Desktop\\word-counter\\TextFile2.txt';
function countRepeatedWords(sentence) {
const words = sentence.split(" ").filter(word => !!word);
const wordMap = {};
for (let word of words) {
const key = word.trim().toLowerCase();
const currentWordCount = wordMap[key];
wordMap[key] = (currentWordCount ?? 0) + 1;
}
const sortedEntries = Object.entries(wordMap).sort(([a,], [b,]) => a.localeCompare(b));
const sortedWordMap = Object.fromEntries(sortedEntries);
// Return both the word map and the sorted version of it
return sortedWordMap;
return wordMap;
}
words = readFileSync(file).toString();
console.log(countRepeatedWords(words));