Advertisement
Guest User

Untitled

a guest
Sep 12th, 2019
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.38 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. //The provided function mostFrequentWord takes a single argument, text.
  7. function mostFrequentWord(text) {
  8.  
  9. //Declares a variable, words, and it holds the value of the function getTokens which takes a single argument, text.
  10. let words = getTokens(text);
  11.  
  12. //Another variable declaration, wordFrequencies, and it holds the value of an empty object.
  13. let wordFrequencies = {};
  14.  
  15. //Standard notation for a for loop. It means, start with i at 0, and repeat this loop as long as i is less than words.length, and
  16. //after every loop, increase i by 1 (i++).
  17. for (let i = 0; i <= words.length; i++) {
  18.  
  19. //If the value of variable, words, at the location i in the array, is in wordFrequencies, found through looping through the //object, add 1 to the wordFrequencies
  20. if (words[i] in wordFrequencies) {
  21. wordFrequencies[words[i]]++;
  22. }
  23.  
  24. //If the value of variable, words, at location i, is NOT found in, wordFrequencies, set the value of wordFrequencies to 1
  25. else {
  26. wordFrequencies[words[i]] = 1;
  27. }
  28. }
  29.  
  30. //Declares a variable, currentMaxKey, and uses the keys method on the on the object prototype of wordFrequencies.
  31. let currentMaxKey = Object.keys(wordFrequencies)[0];
  32.  
  33. //currentMaxCount variable is declared and it holds the value of the variable wordFrequencies taking the argument currentMaxKey
  34. let currentMaxCount = wordFrequencies[currentMaxKey];
  35.  
  36. //for loop where the variable, word, is declared and the wordFrequencies object is looped through looking for that variable.
  37. for (let word in wordFrequencies) {
  38.  
  39. //if statement where if the variable wordFrequencies when passed the argument, word, is greater than the currentMaxCount, perform //the following block of code.
  40. if (wordFrequencies[word] > currentMaxCount) {
  41. //Set the value of currentMaxKey to word.
  42. currentMaxKey = word;
  43.  
  44. //Set the value of currnetMaxCount to wordFrequencies taking the argument, word.
  45. currentMaxCount = wordFrequencies[word];
  46. }
  47. }
  48. //At last we return the currentMaxKey. The purpose of the function mostFrequentWord is to iterate through objects to
  49. //return the word used the most throughout the string provided in the function getTokens.
  50. return currentMaxKey;
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement