Skip to content

Instantly share code, notes, and snippets.

@camckin10
Created April 4, 2017 23:21
Show Gist options
  • Save camckin10/13154a852bbdf1495c625e99fb989845 to your computer and use it in GitHub Desktop.
Save camckin10/13154a852bbdf1495c625e99fb989845 to your computer and use it in GitHub Desktop.
Frequent Word Challenge question answer
Challenge Question Answer
function getTokens(rawString) {
// NB: `.filter(Boolean)` removes any falsy items from an array
return rawString.toLowerCase().split(/[ ,!.";:-]+/).filter(Boolean).sort();
}
/returning a lowercase string which will be
/.split = split takes this expression and splits array based on character in
parenthesis
if character in parenthesis is not in original array, then array will return
original array
/[regular expression]/
/.filter(function) = scan the array, call function on each element in array and remove element where function returns false
/.sort = sorts arrays in place and returns elements in alphabetical order
//mostFrequentWord is an object--first object
//the object has a for loop loops over words(array) to build another object
//when looping over array, if word is already in object, increment word by 1
//if its not in the object it will add it to the obj
// 2nd object keeping in count of frequency of words (currentMaxCount)
//loops over frequency(mostFrequentWord) object to figure out which one of words appears the mos t frequently
//returns word that appears the most (currentMaxKey)
function mostFrequentWord(text) {
var words = getTokens(text);//array that has been sorted
// words= array of strings
var wordFrequencies = {};//empty object
for (var i = 0; i <= words.length; i++) {//for loop
if (words[i] in wordFrequencies) { //array in empty object?
wordFrequencies[words[i]]++;
**//string is indexing in the ith position; will increase by 1 a certain
//amount of times depending on array length.
//
}
else {
wordFrequencies[words[i]]=1;
//words[i] is in the ith position; set the value associated with the key to 1
}
}
var currentMaxKey = Object.keys(wordFrequencies)[0];
**//currentMaxKey = all of keys of object wordFrequencies has value of 0
//currentMaxKey becomes a new object?
var currentMaxCount = wordFrequencies[currentMaxKey];
**//currentMaxCount = adding currentMaxKey object to wordFrequencies object
//using bracket notation ; create new object currentMaxCount to hold all
//key/value pairs from previous 2 objects
for (var word in wordFrequencies)
if (wordFrequencies[word] > currentMaxCount) {
//if object[with newly added array] is greater than currentMaxCount,
currentMaxKey = word;
//currentMaxKey is equal to word array
currentMaxCount = wordFrequencies[word];
//object is equal to object[newly added array]
}
}
return currentMaxKey;
**//return new object with updated keys/values
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment