Guest User

Untitled

a guest
Feb 21st, 2018
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.67 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. // This is the function declaration (mostFrequentWord) with a single argument (text). It is this function that will detect the most frequent word in a body of text.
  6. function mostFrequentWord(text) {
  7. // This is a variable declaration (words) that is assigned to a function (getTokens(text) with the same argument (text) as the parent function.
  8. var words = getTokens(text);
  9. // This variable declaration (wordFrequencies) is assigned to an empty object.
  10. var wordFrequencies = {};
  11. // This is a for loop which will go through each item in an array (words is an array.)
  12. for (var i = 0; i <= words.length; i++) {
  13. // This is a Boolean checking if there is any text in the variable, words, in the object, wordFrequencies.
  14. if (words[i] in wordFrequencies) {
  15. // If true, this statement will check the entire object to see how many times this text appears in it (wordFrequencies).
  16. wordFrequencies[words[i]]++;
  17. }
  18. // If false, this statement equates the object to the value of 1.
  19. else {
  20. wordFrequencies[words[i]]=1;
  21. }
  22. }
  23. // This variable is assigned to the keys of values of the object (wordFrequencies) of the first item in the array.
  24. var currentMaxKey = Object.keys(wordFrequencies)[0];
  25. // This variable is assigned to the
  26. var currentMaxCount = wordFrequencies[currentMaxKey];
  27.  
  28. for (var word in wordFrequencies) {
  29. if (wordFrequencies[word] > currentMaxCount) {
  30. currentMaxKey = word;
  31. currentMaxCount = wordFrequencies[word];
  32. }
  33. }
  34. return currentMaxKey;
  35. }
Add Comment
Please, Sign In to add comment