Skip to content

Instantly share code, notes, and snippets.

@821jieun
Created February 14, 2018 20:23
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 821jieun/611089050e21047f3a552cbe458918f1 to your computer and use it in GitHub Desktop.
Save 821jieun/611089050e21047f3a552cbe458918f1 to your computer and use it in GitHub Desktop.
most frequent word analyzer challenge
function getTokens(rawString) {
// NB: `.filter(Boolean)` removes any falsy items from an array
return rawString.toLowerCase().split(/[ ,!.";:-]+/).filter(Boolean).sort();
//all capitalized letters are turned into lower case letters in the raw string.
//that all lower case string is then being split where punctuation marks are found.
//falsy items are removed.
//the string is then sorted alphabetically and is the return value of the getTokens function call.
}
function mostFrequentWord(text) {
//getTokens function is called with the text and the filtered and alphabetized text is returned
let words = getTokens(text);
let wordFrequencies = {};
//the filtered and sorted text is iterated through
for (let i = 0; i <= words.length; i++) {
//if the word is found in the wordFrequency object, the word's counter is increased by one
if (words[i] in wordFrequencies) {
wordFrequencies[words[i]]++;
} else {
//if the word is not yet found in the wordFrequency object, the word is
//added to the object and its counter is set to 1
wordFrequencies[words[i]] = 1;
}
}
let currentMaxKey = Object.keys(wordFrequencies)[0];
//Object.keys is used to set a word in the wordFrequencies object as the currentMaxKey
//to begin the comparison and itscorresponding counter is set as the currentMaxCount
let currentMaxCount = wordFrequencies[currentMaxKey];
//the wordFrequencies object is then iterated through and each word's counter is compared to the
//currentMaxCount. if the count of the word currently being iterated over is bigger than the value stored in the currentMaxCount, the currentMaxKey is set to the word currently being iterated over and the currentMaxCount's value becomes the count of the currentMaxKey
for (let word in wordFrequencies) {
if (wordFrequencies[word] > currentMaxCount) {
currentMaxKey = word;
currentMaxCount = wordFrequencies[word];
}
}
//once all the words in the wordFrequencies object has been iterated over, the value stored in the currentMaxKey is returned
return currentMaxKey;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment