WEB818
9/24/2019 - 10:02 PM

gistfile1.txt

// getTokens function takes one argument, rawString.
 rawString is a string and the function returns the string into an array of substrings.
 `.split(/[ ,!.";:-]+/)` specifies the characters and spaces for splitting the string
 `.filter(Boolean) removes falsy items from the array 
 `.sort() sorts the array alphabetically. 


function getTokens(rawString) {
 // NB: `.filter(Boolean)` removes any falsy items from an array
 return rawString.toLowerCase().split(/[ ,!.";:-]+/).filter(Boolean).sort();
}

//mostFrequentWord function takes one argument, text. 
 Variable words is assigned to the array of transformed text from the getTokens function. 
 Variable wordFrequencies is assigned to an empty object. 
 mostFrequentWord function will iterate through the entire array passed through the function by 
 the text argument starting at index[0] until the index number equals the number of items in the array. 
 If the word is found in the wordFrequencies object, then the counter will add one to that word's frequency. 
 If the word is not found in the wordFrequencies object, then the word will be added to the object and assigned
 the value of 1.
 
function mostFrequentWord(text) {
 let words = getTokens(text);
 let wordFrequencies = {};
 for (let i = 0; i <= words.length; i++) {
   if (words[i] in wordFrequencies) {
     wordFrequencies[words[i]]++;
   } else {
     wordFrequencies[words[i]] = 1;
   }
 }
 let currentMaxKey = Object.keys(wordFrequencies)[0]; //the wordFrequencies object is passed to Object.keys to get back the keys of the wordFrequencies object returned as an array. The first key [index of 0] in the array is assigned to currentMaxKey variable.
 let currentMaxCount = wordFrequencies[currentMaxKey]; //the currentMaxCount variable is assigned to the number of times the currentMaxKey occurs (defined above as the first key in the array)
 
 //this for loop will iterate through the object wordFrequencies. If a word has a count that is greater than the value of the word in the first position of the array, 
  then the currentMaxKey is assigned to that word and the currentMaxCount is assigned to the number of times that word occurs in the text.
 for (let word in wordFrequencies) {
   if (wordFrequencies[word] > currentMaxCount) {
     currentMaxKey = word;
     currentMaxCount = wordFrequencies[word];
   }
 }
 //ends the function and returns the word with the highest count.
 return currentMaxKey;
}