Skip to content

Instantly share code, notes, and snippets.

@punkrocker178
Created August 22, 2018 04:03
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 punkrocker178/ade60e6e229de394612165874bfa32b6 to your computer and use it in GitHub Desktop.
Save punkrocker178/ade60e6e229de394612165874bfa32b6 to your computer and use it in GitHub Desktop.
Analyze a most frequent word program Thinkful Unit 2 Lesson 6
function getTokens(rawString) {
// NB: `.filter(Boolean)` removes any falsy items from an array
// .split : split words from to to an array,input of spliting is Regex.This Regex means ignore white space character and any other special characters like commas,semi-colon,exclamation marks,etc...
// .sort : sorting words in an alphabetical order.
return rawString.toLowerCase().split(/[ ,!.";:-]+/).filter(Boolean).sort();
}
function mostFrequentWord(text) {
var words = getTokens(text);
console.log(words);
var wordFrequencies = {};
for (var i = 0; i <= words.length; i++) {
// Check if the current word appears in the wordFrequency object then count that word
if (words[i] in wordFrequencies) {
wordFrequencies[words[i]]++;
}
// If not it will be added to the object wordFrequencies
else {
wordFrequencies[words[i]]=1;
console.log(words[i]+":"+wordFrequencies[words[i]]);
}
}
// Find max algorithm
var currentMaxKey = Object.keys(wordFrequencies)[0];
var currentMaxCount = wordFrequencies[currentMaxKey];
for (var word in wordFrequencies) {
if (wordFrequencies[word] > currentMaxCount) {
currentMaxKey = word;
currentMaxCount = wordFrequencies[word];
}
}
return currentMaxKey;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment