Advertisement
Guest User

Untitled

a guest
Apr 18th, 2019
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.75 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. // The getTokens function is first asking for an input of a string(rawString).
  6. // Then from the many different methods it alters the string in these ways:
  7. // 1) lower case strings
  8. // 2) It turns the string into an array that creates a new substring when /[ ,!.";:-]+/ is present.
  9. // 3) It also only returns True statements.
  10. // 4) Lastly it sorts the array alphabetically.
  11.  
  12. function mostFrequentWord(text) {
  13. let words = getTokens(text);
  14. // It sets the variable "words" with a value of a string from getTokens.
  15. let wordFrequencies = {};
  16. // wordFrequencies" variable is set as an empty object in which a number will be stored.
  17. for (let i = 0; i <= words.length; i++) {
  18. if (words[i] in wordFrequencies) {
  19. wordFrequencies[words[i]]++;
  20. } else {
  21. wordFrequencies[words[i]] = 1;
  22. }
  23. // In this loop it states that if a word appears in the object, then the count is increased, and if it does not appear, then it's value is 1."
  24. }
  25. let currentMaxKey = Object.keys(wordFrequencies)[0];
  26. let currentMaxCount = wordFrequencies[currentMaxKey];
  27. // The variable "currentMaxKey" that sets the key at 0 and "currentMaxCount" is a variable that gives the value shows up in the object.
  28.  
  29. for (let word in wordFrequencies) {
  30. if (wordFrequencies[word] > currentMaxCount) {
  31. currentMaxKey = word;
  32. currentMaxCount = wordFrequencies[word];
  33. }
  34. // This loop means that that if the word count is larger than value of the currentMaxCount, then the values change to reflect the "wordFrequencies" .
  35. }
  36. return currentMaxKey;
  37. // This returns the word with the highest number.
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement