Created
February 24, 2018 07:12
-
-
Save jeffreymahmoudi/eacd9e77be0dfafd7712232f3c148419 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 | |
return rawString.toLowerCase().split(/[ ,!.";:-]+/).filter(Boolean).sort(); | |
} | |
function mostFrequentWord(text) { | |
// Turn the text into an array of tokens | |
let words = getTokens(text); | |
// Create an empty object to hold data about each word. | |
let wordFrequencies = {}; | |
// Loop through each token in words array. | |
for (let i = 0; i <= words.length; i++) { | |
// Increment value of word in wordFrequencies if current word is already in wordFrequencies. | |
if (words[i] in wordFrequencies) { | |
wordFrequencies[words[i]]++; | |
// Add key and value for word to be added to wordFrequences object. | |
} else { | |
wordFrequencies[words[i]] = 1; | |
} | |
} | |
// Set default values for testing max value. | |
let currentMaxKey = Object.keys(wordFrequencies)[0]; | |
let currentMaxCount = wordFrequencies[currentMaxKey]; | |
// Iterate wordFrequencies and update currentMax values if logic satisfied | |
for (let word in wordFrequencies) { | |
if (wordFrequencies[word] > currentMaxCount) { | |
currentMaxKey = word; | |
currentMaxCount = wordFrequencies[word]; | |
} | |
} | |
return currentMaxKey; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment