function getTokens(rawString) {
// NB: `.filter(Boolean)` removes any falsy items from an array
// this function takes a string as an argument, changes all letters to
// lowercase, and splits the string when it encounters at least one of
// these punctuation marks: ,!.";:-
// then the string is filtered as described above and sorted by unicode values.
return rawString.toLowerCase().split(/[ ,!.";:-]+/).filter(Boolean).sort();
}
function mostFrequentWord(text) {
// initialize variables to be used later
// words is an array of strings created by getTokens()
let words = getTokens(text);
// this will contain the appearance count of each word
let wordFrequencies = {};
// loop through the array of words created earlier, and...
for (let i = 0; i <= words.length; i++) {
if (words[i] in wordFrequencies) {
// ...if a word already exists in the wordFrequencies object,
// increase its appearance count.
wordFrequencies[words[i]]++;
} else {
// ...if a word is appearing in the array for the first time,
// add it to the wordFrequencies object and set its count to 1.
wordFrequencies[words[i]] = 1;
}
}
// currentMaxKey is the first word in the wordFrequencies object
// and currentMaxCount is the appearance count of that word.
let currentMaxKey = Object.keys(wordFrequencies)[0];
let currentMaxCount = wordFrequencies[currentMaxKey];
// loop through the wordFrequencies object we created, and...
for (let word in wordFrequencies) {
if (wordFrequencies[word] > currentMaxCount) {
// ...if the word in the current iteration has a larger appearance count
// than the current word with the largest appearance count,
// set that word to be the new word with the most appearances.
// do this until the word with the largest count overall is in currentMaxKey.
currentMaxKey = word;
currentMaxCount = wordFrequencies[word];
}
}
// return the word with the most appearances.
return currentMaxKey;
}