Advertisement
Guest User

Untitled

a guest
Apr 25th, 2017
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.52 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. //returns the raw string in all lower case so that case will not affect matching, clears punctuation, and sorts the array in alphabetical order
  5. }
  6.  
  7. function mostFrequentWord(text) {
  8. var words = getTokens(text);
  9. //runs the getTokens function on the entered text
  10. var wordFrequencies = {};
  11. //create an empty object for wordFrequencies
  12. for (var i = 0; i <= words.length; i++) {
  13. //run the following loop as long as i is less than or equal to length of the words array
  14. if (words[i] in wordFrequencies) {
  15. wordFrequencies[words[i]]++;
  16. }
  17. else {
  18. wordFrequencies[words[i]]=1;
  19. }
  20. //increment the count for a particular word if found else count is just one
  21. }
  22. var currentMaxKey = Object.keys(wordFrequencies)[0];
  23. //set the var currentMaxKey to the keys of wordFrequencies
  24. var currentMaxCount = wordFrequencies[currentMaxKey];
  25. //sets the var currentMaxCount to the currentMaxKey of wordFrequencies
  26. for (var word in wordFrequencies) {
  27. //loop through the words in wordFrequencies
  28. if (wordFrequencies[word] > currentMaxCount) {
  29. currentMaxKey = word;
  30. currentMaxCount = wordFrequencies[word];
  31. //if the word in wordFrequencies is greater than the currentMaxCount, se currentMaxKey to equal the word and the currentMaxCount to equal the word frequencies
  32. }
  33.  
  34. }
  35. return currentMaxKey;
  36. //return the results
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement