Advertisement
Guest User

Untitled

a guest
Sep 18th, 2019
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.05 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. // Get tokens using getToken function
  8. let words = getTokens(text);
  9. let wordFrequencies = {};
  10. //This loops through every word to count the frequencies of word
  11. for (let i = 0; i <= words.length; i++) {
  12. // Inspects to see if word is already in object wordFrequencies
  13. if (words[i] in wordFrequencies) {
  14. wordFrequencies[words[i]]++;
  15. } else {
  16. wordFrequencies[words[i]] = 1;
  17. }
  18. } //Gets first key through wordFrequencies
  19. let currentMaxKey = Object.keys(wordFrequencies)[0];
  20. let currentMaxCount = wordFrequencies[currentMaxKey];
  21.  
  22. for (let word in wordFrequencies) {
  23. //Again, loops through word to find highest frequency word
  24. if (wordFrequencies[word] > currentMaxCount) {
  25. currentMaxKey = word;
  26. currentMaxCount = wordFrequencies[word];
  27. }
  28. }
  29. //returns highest count word
  30. return currentMaxKey;
  31. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement