Guest User

Untitled

a guest
Feb 21st, 2018
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.37 KB | None | 0 0
  1. function getTokens(rawString) {
  2. //BB: This function returns a sorted array of all words in rawString
  3. // NB: `.filter(Boolean)` removes any falsy items from an array
  4. return rawString.toLowerCase().split(/[ ,!.";:-]+/).filter(Boolean).sort();
  5. }
  6.  
  7. function mostFrequentWord(text) {
  8. let words = getTokens(text); // BB: get sorted array of all words in 'text'
  9. let wordFrequencies = {}; // BB: init object -- list of keys (words) and frequencies
  10.  
  11. // BB: loop through each word
  12. // if word not already a key,
  13. // add the key and set its value to 1,
  14. // otherwise increment its value by 1
  15. for (let i = 0; i <= words.length; i++) {
  16. if (words[i] in wordFrequencies) {
  17. wordFrequencies[words[i]]++;
  18. } else {
  19. wordFrequencies[words[i]] = 1;
  20. }
  21. }
  22.  
  23. // BB: init "most frequent word/key" and count vars:
  24. let currentMaxKey = Object.keys(wordFrequencies)[0];
  25. let currentMaxCount = wordFrequencies[currentMaxKey];
  26.  
  27. // BB: for each key in wordFrequencies, compare its count
  28. // to the max count, and if it's greater, set the
  29. // MaxKey and MaxCount to this Key and Count
  30. for (let word in wordFrequencies) {
  31. if (wordFrequencies[word] > currentMaxCount) {
  32. currentMaxKey = word;
  33. currentMaxCount = wordFrequencies[word];
  34. }
  35. }
  36. // BB: return the result of the MaxKey
  37. // (word with greatest frequency)
  38. return currentMaxKey;
  39. }
Add Comment
Please, Sign In to add comment