Guest User

Untitled

a guest
Jan 22nd, 2019
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.49 KB | None | 0 0
  1. function getTokens(rawString) {
  2. // NB: `.filter(Boolean)` removes any falsy items from an array
  3. //this function returns an array of words from rawString split at the characters [ ,!.";:-]+ all lower-cased and sorted alphabetically
  4. return rawString.toLowerCase().split(/[ ,!.";:-]+/).filter(Boolean).sort();
  5. }
  6.  
  7. function mostFrequentWord(text) {
  8. //we get an array of words from text that is ordered
  9. let words = getTokens(text);
  10. //this object keeps track of each time a word is mentioned
  11. let wordFrequencies = {};
  12. //we loop through the array and add it to our object or increment it's value by 1
  13. for (let i = 0; i <= words.length; i++) {
  14. if (words[i] in wordFrequencies) {
  15. wordFrequencies[words[i]]++;
  16. } else {
  17. wordFrequencies[words[i]] = 1;
  18. }
  19. }
  20. //currentMaxKey keeps track of the key that has the max value in the object
  21. let currentMaxKey = Object.keys(wordFrequencies)[0];
  22. //currentMaxCount keeps track of the number of times the currentMaxKey was in text
  23. let currentMaxCount = wordFrequencies[currentMaxKey];
  24.  
  25. //we loop through each word in our frequencies object and compare its value with the currentMaxCount and change the currentMaxKey if the value is greater than the currentMaxCount. Then we update the currentMaxCount
  26. for (let word in wordFrequencies) {
  27. if (wordFrequencies[word] > currentMaxCount) {
  28. currentMaxKey = word;
  29. currentMaxCount = wordFrequencies[word];
  30. }
  31. }
  32. //we return the word that comes up the most times
  33. return currentMaxKey;
  34. }
Add Comment
Please, Sign In to add comment