Created
May 2, 2017 22:29
-
-
Save iancover/07d9487540c2e7a21fac12b068306477 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
function getTokens(rawString) { | |
// NB: `.filter(Boolean)` removes any falsy items from an array | |
// method '.toLowerCase' makes all the characters in the string 'rawString' smallcaps | |
// method '.split' splits each item in the string with the characters passed | |
// method '.sort()' will sort the string alphabetically | |
return rawString.toLowerCase().split(/[ ,!.";:-]+/).filter(Boolean).sort(); | |
} | |
function mostFrequentWord(text) { | |
// locally creating a variable 'words' that calls the function getTokens passing the argument on this function | |
var words = getTokens(text); | |
// creating a variable 'wordFrequencies' thats an object | |
var wordFrequencies = {}; | |
// loop that iterates thru the length of 'words' variable, at this point it understands that 'getTokens' function | |
// produces an array | |
for (var i = 0; i <= words.length; i++) { | |
// logic that accesses 'i' position in array and states 'if 'i'position in words is 'in' wordFrequencies | |
if (words[i] in wordFrequencies) { | |
// then the key in wordFrequencies 'words[i]' increments and this is what marks how frequent the word is showing | |
wordFrequencies[words[i]]++; | |
} | |
// otherwise the key in wordFrequencies 'words[i]' equals 1 so its not repeating in the object | |
else { | |
wordFrequencies[words[i]]=1; | |
} | |
} | |
// this var states that the current max repetitions of keys or words is 0 | |
var currentMaxKey = Object.keys(wordFrequencies)[0]; | |
// this var is equivalent to the key 'currentMaxKey' in wordFrequencies | |
var currentMaxCount = wordFrequencies[currentMaxKey]; | |
// this loop is gonna continue looking for the 'word' in wordFrquencies | |
for (var word in wordFrequencies) { | |
// if the word in wordFrequencies is greater than the currentMaxCount | |
if (wordFrequencies[word] > currentMaxCount) { | |
// then assign that word as the amount of times | |
currentMaxKey = word; | |
// and current max count to that word so it doesnt count it again and can move on to next | |
currentMaxCount = wordFrequencies[word]; | |
} | |
} | |
return currentMaxKey; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment