Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save michaelablackham/b1e6f10acc1b3bf82b95ce8bf4970336 to your computer and use it in GitHub Desktop.
Save michaelablackham/b1e6f10acc1b3bf82b95ce8bf4970336 to your computer and use it in GitHub Desktop.
Challenge: analyze a most frequent word program
function getTokens(rawString) {
// NB: `.filter(Boolean)` removes any falsy items from an array
return rawString.toLowerCase().split(/[ ,!.";:-]+/).filter(Boolean).sort();
/*returns a raw string, converts to lower case, splots the words/letters
by the user of spaces, commas, exclamation points, periods quotes,
semicolons, colons, hyphens and sort them in alphabetical order after
finding out if it is true or not*/
}
function mostFrequentWord(text) {
var words = getTokens(text);
/* create a variable called word which passes the "get tokens" function
with any string of text from the text parameter */
var wordFrequencies = {};
/* create a wordFrequencies variable which is equal to an empty object
that we will be filling in */
for (var i = 0; i <= words.length; i++) {
/* creating a for loop starting at the first object until the last
item within the word array and */
if (words[i] in wordFrequencies) {
/* if the current word within the empty is object is true, then run
this function below*/
wordFrequencies[words[i]]++;
/* get the current object from wordFrequencies and add to it*/
}
else {
/* if the current word within the empty object is false, then run
this funcion below */
wordFrequencies[words[i]]=1;
/* get the current object from wordFrequencies and have it equal to 1*/
}
}
var currentMaxKey = Object.keys(wordFrequencies)[0];
/* create a variable called currentMaxKey which takes the object */
var currentMaxCount = wordFrequencies[currentMaxKey];
/* create a currentmaxCount variable which passes the wordFrequencies
object with the currentMaxKey parameter*/
for (var word in wordFrequencies) {
if (wordFrequencies[word] > currentMaxCount) {
/* if the wordFrequencies text amount is greater than the currentMaxCount
dicated from the variable out side of here, then change the variables below */
currentMaxKey = word;
/* currentMaxKey is now set to the word parameter */
currentMaxCount = wordFrequencies[word];
/* currentMaxCount is not set to the wordFrequencies parameter */
}
}
return currentMaxKey;
/* return the final output for the new current max key */
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment