Last active
October 12, 2019 15:37
-
-
Save oaluna/9ae8a7940cfe78a3d70f4dbd3a7d2368 to your computer and use it in GitHub Desktop.
Most Frequent Word Analyzer Challenge - Oscar Luna
This file contains hidden or 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) { // this is our function that takes the argument text. | |
let words = getTokens(text); // this tells the computer that every true item in the text is a word | |
let wordFrequencies = {} //wordFrequencies is an array that iterates through the whole text. | |
for (let i = 0; i <= words.length; i++) { | |
if (words[i] in wordFrequencies) { | |
wordFrequencies[words[i]]++; | |
//if a word i occurs, then wordFrequencies increments by 1 every time words[i] is true throughout this iteration; else it stays equal to 1. | |
} else { | |
wordFrequencies[words[i]] = 1; | |
} | |
} | |
let currentMaxKey = Object.keys(wordFrequencies)[0]; | |
let currentMaxCount = wordFrequencies[currentMaxKey]; | |
//This takes every key value of the object (word), and creates a counter for the highest count for a word. | |
for (let word in wordFrequencies) { | |
if (wordFrequencies[word] > currentMaxCount) { | |
currentMaxKey = word; | |
currentMaxCount = wordFrequencies[word]; | |
} | |
} | |
return currentMaxKey; | |
} | |
//If the frequency of a word becomes greater than the currentMaxCount, then currentMaxKey's value is updated to the word's frequency, and the counter for highest frequency goes to the new most frequent word-- currentMaxKey. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment