Advertisement
Guest User

Untitled

a guest
Apr 20th, 2019
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.24 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.  
  7. // counting the amount of time a word/character pops up and sorting them and to show which word/character comes up the most.
  8.  
  9.  
  10. function mostFrequentWord(text) {
  11. let words = getTokens(text);
  12. let wordFrequencies = {};
  13.  
  14. // putting the strings into a loop and counting the frequency of the words/characters in the string or leaving them as 1 if the character
  15. only comes up once
  16.  
  17. for (let i = 0; i <= words.length; i++) {
  18. if (words[i] in wordFrequencies) {
  19. wordFrequencies[words[i]]++;
  20. } else {
  21. wordFrequencies[words[i]] = 1;
  22. }
  23. }
  24. // starting from index 0 and adding the counts to wordFrequencies.
  25.  
  26. let currentMaxKey = Object.keys(wordFrequencies)[0];
  27. let currentMaxCount = wordFrequencies[currentMaxKey];
  28.  
  29. //making currentMaxKey equal the count of "word" and equalling the total into the frequencies and then returning the currentMaxKey.
  30.  
  31. for (let word in wordFrequencies) {
  32. if (wordFrequencies[word] > currentMaxCount) {
  33. currentMaxKey = word;
  34. currentMaxCount = wordFrequencies[word];
  35. }
  36. }
  37. return currentMaxKey;
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement