Skip to content

Instantly share code, notes, and snippets.

@mcshakes
Created January 10, 2018 13:42
Show Gist options
  • Save mcshakes/139b0b49b30b48a3f3fd1224b0baa423 to your computer and use it in GitHub Desktop.
Save mcshakes/139b0b49b30b48a3f3fd1224b0baa423 to your computer and use it in GitHub Desktop.
HOW IT WORKS:
- When mostFrequentWord is invoked, it takes a bunch of text as an argument.
- This text goes throught the separate helper function getTokens, where it is saved as the variable "words".
(i) Within getTokens, it is lowercased, and split along normal sentence punctuation. (see observation 1).
(ii) It is then sorted alphabetically and stored in array.
- wordFrequencies is declared as empty hash object.
- Then we iterate through the words array:
(i) if words exist within the wordFrequencies already, add to the counter with ++.
(ii) Else, start at 1. (see observation 2)
- currentMaxKey variable is the key Object within wordFrequencies (hint: we get a word/string).
- We grab the value with `wordFrequencies[currentMaxKey]` and save as currentMaxCount.
- Looping through words within wordFrequencies,
(i) if the word we are "studying" within wordFrequencies is larger than currentMaxCount,
(ii) the currentMaxKey becomes the most frequent key (I tend to call this variable a pointer).
(iii) and the currentMaxCount becomes that new value for the word we found in step (ii).
Finally, we return the currentMaxKey; the word most frequently used.
OBSERVATIONS AND NOTES:
1) A sentence ending in period results in "" as part of last array element
-- example let cb = "Hey There." becomes [ 'hey', 'there', '' ].
-- I guess this is why we have Object.filter(Boolean) to remove that falsey piece.
2) Without this piece, I played around and wrote a dummy function that created an object looking like
{"hello": Nan, "world": NaN}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment