Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jeffreymahmoudi/eacd9e77be0dfafd7712232f3c148419 to your computer and use it in GitHub Desktop.
Save jeffreymahmoudi/eacd9e77be0dfafd7712232f3c148419 to your computer and use it in GitHub Desktop.
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