Skip to content

Instantly share code, notes, and snippets.

@willwalker753
Created February 26, 2020 19:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save willwalker753/da5622959b4dc2a956845ad4a18c239c to your computer and use it in GitHub Desktop.
Save willwalker753/da5622959b4dc2a956845ad4a18c239c to your computer and use it in GitHub Desktop.
most frequent word analyzer challenge
function getTokens(rawString) {
return rawString.toLowerCase().split(/[ ,!.";:-]+/).filter(Boolean).sort();
//removes punctuation from text
}
function mostFrequentWord(text) {
let words = getTokens(text); //assigns text without punctuation to new variable named words
let wordFrequencies = {}; //creates empty object for results
for (let i = 0; i <= words.length; i++) { //loops through length of words
if (words[i] in wordFrequencies) { //if the word is already in the object add 1 to its count
wordFrequencies[words[i]]++;
} else { //if the word isnt in the object add it with a value of 1
wordFrequencies[words[i]] = 1;
}
}
let currentMaxKey = Object.keys(wordFrequencies)[0]; //creates variable to hold the current word with the most uses
let currentMaxCount = wordFrequencies[currentMaxKey]; //creates variable to hold the current max keys value
for (let word in wordFrequencies) { //goes over all words in word frequencies
if (wordFrequencies[word] > currentMaxCount) { //if the word has more uses than the current max one does then make the one with more uses the current max word
currentMaxKey = word; //assigns the new max words key
currentMaxCount = wordFrequencies[word]; //assigns the new max words value
}
}
return currentMaxKey; //returns the word with the most uses
}
/*Overall this program removes punctuation from text, then counts how many times each different word is used in the text, then compares the numbers of uses to find
which is greatest and returns it*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment