Created
February 22, 2019 03:23
-
-
Save jcharles22/fcf83b730607600b9a0d29f95f93c485 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function getTokens(rawString) { | |
// NB: `.filter(Boolean)` removes any falsy items from an array | |
// returns an array of strings. splits it by symbols and spaces and has been sorted. | |
return rawString.toLowerCase().split(/[ ,!.";:-]+/).filter(Boolean).sort(); | |
} | |
// text is a body of text like a paragraph from a novel, or song lyrics | |
function mostFrequentWord(text) { | |
// declares words and passes text to the function getTokens() and returns it as an array of strings. | |
let words = getTokens(text); | |
// creates an empty object | |
let wordFrequencies = {}; | |
// loops through the whole array of words | |
for (let i = 0; i <= words.length; i++) { | |
// check to see if word at index i is in wordFrequencies object | |
if (words[i] in wordFrequencies) { | |
// if word is already in wordFrequencies class adds +1 to the counter | |
wordFrequencies[words[i]]++; | |
} else { | |
// if the current word is not in the wordFrequencies class create a counter and set it to 1 | |
wordFrequencies[words[i]] = 1; | |
} | |
} | |
// sets the currentMaxKey to the first string in the array | |
let currentMaxKey = Object.keys(wordFrequencies)[0]; | |
// sets currentMaxCount to the | |
let currentMaxCount = wordFrequencies[currentMaxKey]; | |
// go through each word in the class wordFrequencies to find the greatest | |
for (let word in wordFrequencies) { | |
// if this word count is greater than currentMaxCount set the Key and Counter to the currnet | |
if (wordFrequencies[word] > currentMaxCount) { | |
currentMaxKey = word; | |
currentMaxCount = wordFrequencies[word]; | |
} | |
} | |
// return the word with the greates word count | |
return currentMaxKey; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment