Last active
April 1, 2020 06:10
-
-
Save lucasjlatour/023d23a7a4287f896d2b46fb032b6c86 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
//this function seems to split up words, make them all lowercase, remove all non words, and then return them in an array. It also sorts them in alphabetical order | |
function getTokens(rawString) { | |
// NB: `.filter(Boolean)` removes any falsy items from an array | |
return rawString.toLowerCase().split(/[ ,!.";:-]+/).filter(Boolean).sort(); | |
} | |
function mostFrequentWord(text) { // declares function | |
let words = getTokens(text); // calls the getTokens function and stores all the text in words array | |
let wordFrequencies = {}; //creates an empty object | |
/*This for loop goes through each word in the words array. It figures out if the word is already in the wordFrequencies object. If it is, it adds to one to the frequency value of that word. If it's not it adds the word as a key to the object and sets the frequency value to 1 for that word.*/ | |
for (let i = 0; i <= words.length; i++) { | |
if (words[i] in wordFrequencies) { | |
wordFrequencies[words[i]]++; | |
} else { | |
wordFrequencies[words[i]] = 1; | |
} | |
} | |
let currentMaxKey = Object.keys(wordFrequencies)[0]; //starts with the first word in our object. | |
let currentMaxCount = wordFrequencies[currentMaxKey]; //represents the count value of each word as we compare their counts. Starts with the first word's frequency value. | |
/*Compares the word counts of each word to the current max count word. Sees if the word frequency value is larger, and if it is assigns key with higher count to the current max key and also assings that count to the current max count*/ | |
for (let word in wordFrequencies) { | |
if (wordFrequencies[word] > currentMaxCount) { | |
currentMaxKey = word; | |
currentMaxCount = wordFrequencies[word]; | |
} | |
} | |
//returns the word that occurs the most | |
return currentMaxKey; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment