Guest User

Untitled

a guest
Jul 18th, 2018
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.58 KB | None | 0 0
  1. function getTokens(rawString) {
  2. // NB: `.filter(Boolean)` removes any falsy items from an array
  3. return rawString.toLowerCase().split(/[ ,!.";:-]+/).filter(Boolean).sort();
  4. }
  5.  
  6. function mostFrequentWord(text) {
  7. let words = getTokens(text); // get an array words, split based on the regex, lowercase them for ease of comparison, removed boolean values
  8. let wordFrequencies = {}; //create an object to hold the words
  9. for (let i = 0; i <= words.length; i++) { //iterate over the word array
  10. if (words[i] in wordFrequencies) {
  11. wordFrequencies[words[i]]++; //if the word has has already been added to the object, add 1 to its count
  12. } else {
  13. wordFrequencies[words[i]] = 1; // this word isnt in the object yet so add it and set its count to 1
  14. }
  15. }
  16. let currentMaxKey = Object.keys(wordFrequencies)[0]; //to start somewhere, lets set our max word to the first word in keys of object
  17. let currentMaxCount = wordFrequencies[currentMaxKey]; // same thing here but setting to the count of our first key
  18.  
  19. for (let word in wordFrequencies) { //iterate over our word object
  20. if (wordFrequencies[word] > currentMaxCount) { //now we compare if the current word we are looking at has a higher count than whatever currentMaxCount is set to
  21. currentMaxKey = word; //if we are here it means we have a new high count so set our current high word to max
  22. currentMaxCount = wordFrequencies[word]; //same thing here but with the count value of our new high word
  23. }
  24. }
  25. return currentMaxKey; //now that weve run through the entire object we know what our highest count word is so return it
  26. }
Add Comment
Please, Sign In to add comment