Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function mostFrequentWord takes a single argument - text. variable words uses that argument to call getTokens function.
- getTokens function
- getTokens function 'cleans' text.. first method changes all the letters to lower case, then `split` separates
- string into words if there is a space or any of the '/[,!.";:-]+/' symbols. Next, `.filter(Boolean)` removes any items
- that are not literals with true and false value. lastly `sort` arranges words in alphabetical order.
- getTokens function returns us an array of alphabetically organised separate words that we will use in mostFrequentWord.
- second local variable in mostFrequentWord is empty object.
- for loop starts at 0 index and counts through words array taking one word at the time as an argument.
- if statement checks if that word has been already added into wordFrequencies object.
- If No then it places a key into an object assigns a value of 1. If it already exists, then it adds 1 to the value of the word.
- When the loop is finished we have wordFrequencies object with `word` as key and number as a value of how many times
- that word occurred in the words array.
- `currentMaxKey` is the first Key of wordFrequencies
- `currentMaxCount` is the value of `currentMaxKey`
- for in loop iterates over the keys of the object `wordFrequencies` where `word` is the key. wordFrequencies[word] is the value of the current key.
- if the value of the current key is higher than the `currentMaxCount`, we change the value of the `currentMaxKey` to the current key (`word`)
- and we change the value of `currentMaxCount` to the value of the current key (`wordFrequencies[word]`)
- if the value of the current key is NOT higher than the `currentMaxCount`, no reassignment occurs and the for in loop continues.
- finally once the loop has finished we return the currentMaxKey.
Add Comment
Please, Sign In to add comment