Advertisement
Guest User

Untitled

a guest
Jul 17th, 2019
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.74 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. //declairing the function and using the object text as an argument
  7. function mostFrequentWord(text) {
  8. //declairing the variable words will be used to save the function written just after with getTokens
  9. let words = getTokens(text);
  10. //declairing the wordFrequencies to be equal to an empty object
  11. let wordFrequencies = {};
  12. //a loop that will increase as long as i is less than or equal to the length of the variable words
  13. for (let i = 0; i <= words.length; i++) {
  14. //if a word appears that is already in the wordFrequencies then it will add 1 to the counter
  15. if (words[i] in wordFrequencies) {
  16. wordFrequencies[words[i]]++;
  17. } else {
  18. //If the word hasnt happened yet it will make the counter equal to 1
  19. wordFrequencies[words[i]] = 1;
  20. }
  21. }
  22. //Declares a variable that calls on tghe first item within the wordFrequencies object
  23. let currentMaxKey = Object.keys(wordFrequencies)[0];
  24. //declares that a variable that is equal to the value of the currentMaxKey is within the wordFrequencies object
  25. let currentMaxCount = wordFrequencies[currentMaxKey];
  26.  
  27. //makes a loop that checks if the newest iteration provides a word that is greater than the current most frequent then it will become th
  28. new currentMaxKey, it will also change its value according to the number of times the word occurred
  29. for (let word in wordFrequencies) {
  30. if (wordFrequencies[word] > currentMaxCount) {
  31. currentMaxKey = word;
  32. currentMaxCount = wordFrequencies[word];
  33. }
  34. }
  35. //returns the current most frequent word along with the number of times it appeared
  36. return currentMaxKey;
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement