Advertisement
Guest User

Untitled

a guest
Jun 26th, 2017
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.42 KB | None | 0 0
  1. function getTokens(rawString) {
  2. // NB: `.filter(Boolean)` removes any falsy items from an array
  3. // .lowercase changes all words in the array to lowercase and .split removes and of the characterd in the braces
  4. return rawString.toLowerCase().split(/[ ,!.";:-]+/).filter(Boolean).sort();
  5. }
  6.  
  7. //this line is declaring the function and using (text) as the argument.
  8. function mostFrequentWord(text) {
  9. // the variable words has been declared as the getTokens Function from above and text is the argument.
  10. //getTokens puts all of the words in the string into an array
  11. var words = getTokens(text);
  12. // the variable wordFrequencies is being declared as an object that has not been defined yet that the words from
  13. //the array will be put into
  14. var wordFrequencies = {};
  15. //this is a for loop that has been created to go through the words array that is in the getTokens function and
  16. //going to go through the full length of the array
  17. for (var i = 0; i <= words.length; i++) {
  18. // this is if statement will be run through each loop. If anything in words index is in wordFrequencies the
  19. //statement below it will be run and keep adding 1 more to it
  20. if (words[i] in wordFrequencies) {
  21. wordFrequencies[words[i]]++;
  22. }
  23. //if the if statement above does not eqaul to true then this else statement will run. If there is no more then 1 of the
  24. // specific word it will just = 1
  25. else {
  26. wordFrequencies[words[i]]=1;
  27. }
  28. }
  29.  
  30. // the currentMaxKey is the list of keys with an object
  31. var currentMaxKey = Object.keys(wordFrequencies)[0];
  32.  
  33. //the variable currentMaxCount is being declared as the currentMaxKey that is declared above from the
  34. //wordFrequencies array
  35. var currentMaxCount = wordFrequencies[currentMaxKey];
  36.  
  37. //this is a for loop that will be run through the properties word in the wordFrequencies object
  38. for (var word in wordFrequencies) {
  39.  
  40. // this is an if statement that will execute if wordFrequencies[word] is greater then currentMaxCount. The word with the current
  41. // max count will be the one that takes p
  42. if (wordFrequencies[word] > currentMaxCount) {
  43.  
  44. // the var currentMaxKey should be declared as word - the workd is the value of the highest count
  45. //and the var currentMaxCount will be declared as wordFrequencies[word];
  46. currentMaxKey = word;
  47. currentMaxCount = wordFrequencies[word];
  48. }
  49. }
  50. //Returns the key value of the most used word
  51. return currentMaxKey;
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement