Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Williams-Christopher/8fdb362b5eabf6cbcd98d8a775185e30 to your computer and use it in GitHub Desktop.
Save Williams-Christopher/8fdb362b5eabf6cbcd98d8a775185e30 to your computer and use it in GitHub Desktop.
Module 5 - Checkpoint 12 - Grokking
function getTokens(rawString)
This function accepts a string and returns an array containing all the truthy words in it.
First it takes in a string, forces it to lower case characters, splits the string into an array using a regular expression, creates a new array of truthy items by filtering 'falsy' items from the split array, and finally sorts the resulting array in alpha descending order. Then the array is returned to the calling function.
function mostFrequentWord(text)
This function takes in a string and returns the first word most frequently found in it.
The function first takes the string passed to it and passes it to getTokens(rawString), receiving back an array of strings to process. It then creates an empty object, wordFrequencies, which it checks for the existence of strings from the token array, using bracket notation to add to the wordFrequencies object those words that don't exist (with a count of one) and incrementing by one those words that it finds.
The last portion of the function finds the first word with the highest frequency count. Two variables are declared, currentMaxKey to hold the value of the first key in the wordFrequencies object by using Object.keys(), and currentMaxCount to hold the frequency value for it. A for loop is used to iterate through the keys in the wordFrequencies object, comparing the current key's value to the currentMaxCount. If the frequency count is higher, the new value is captured and the associated key is stored in currentMaxKey. If the frequency count is lower, the loop moves on. When the loop is complete, the value of currentMaxKey is returned to the calling function.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment