Created
April 21, 2018 07:17
-
-
Save vaibhavhrt/4fa41405ef3caec330b1ef0d3a19bad6 to your computer and use it in GitHub Desktop.
Challenge: analyze a most frequent word program
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(); | |
//split() splits the paragraph into words using regular expression | |
} | |
function mostFrequentWord(text) { | |
var words = getTokens(text); //use getTokens to get an array of words from the paragraoh text | |
var wordFrequencies = {}; //defing an object to save frequency of every word | |
for (var i = 0; i <= words.length; i++) { //loop to iterate through the array of words | |
if (words[i] in wordFrequencies) { | |
wordFrequencies[words[i]]++; //if the current word already exists in the object, increase its frequecy count by 1 | |
} | |
else { | |
wordFrequencies[words[i]]=1; //if the current word doesn't already exists in the object add a new key for that word and set its value to 1 | |
} | |
} | |
var currentMaxKey = Object.keys(wordFrequencies)[0]; | |
var currentMaxCount = wordFrequencies[currentMaxKey]; | |
for (var word in wordFrequencies) { //loop to ierate through the object and find the valoue with highest frequency | |
if (wordFrequencies[word] > currentMaxCount) { | |
currentMaxKey = word; | |
currentMaxCount = wordFrequencies[word]; | |
} | |
} | |
return currentMaxKey; //return that highest frequency key | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment