Advertisement
Guest User

Untitled

a guest
Aug 19th, 2019
73
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. //Changing the string to all lower-case, putting spaces(?) between common possible symbols and characters, then filters by Boolean items only (so no symbols), then sorts alphabetically and returns it. //
  6.  
  7. function mostFrequentWord(text) {
  8. //Pulls array/items from above?
  9.  
  10. let words = getTokens(text);
  11. let wordFrequencies = {};
  12. //Makes an object called wordFrequencies, then starts building a loop that goes over the array from getTokens
  13.  
  14. for (let i = 0; i <= words.length; i++) {
  15. if (words[i] in wordFrequencies) {
  16. wordFrequencies[words[i]]++;
  17. } else {
  18. wordFrequencies[words[i]] = 1;
  19. }
  20. //If a word in wordFrequencies appears more than once, ups value of word[i] by one. If hasn’t seen before, logs it as word[i]=1
  21. }
  22.  
  23. let currentMaxKey = Object.keys(wordFrequencies)[0];
  24. //Makes array called currentMaxKey, made of keys from wordFrequencies.
  25.  
  26. let currentMaxCount = wordFrequencies[currentMaxKey];
  27. //Makes an obj currentMaxCount is contains the most common key and the number of times it appears
  28.  
  29. for (let word in wordFrequencies) {
  30. if (wordFrequencies[word] > currentMaxCount) {
  31. currentMaxKey = word;
  32. currentMaxCount = wordFrequencies[word];
  33. }
  34. //Makes a loop that checks if a word in wordFrequencies appears more than the currentMaxCount. If so, changes that word key and its frequency to the new currentMaxCount. The word then becomes the currentMaxKey.
  35. }
  36. return currentMaxKey;
  37. //Displays most common word in the text
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement