Advertisement
Guest User

Untitled

a guest
Jul 15th, 2019
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.69 KB | None | 0 0
  1. // The getTokens function is a filtering function with the arguement rawstring. It will return an array
  2. of lowercase data elements that splits on a sequence of one or more commas or whitespace so that it will not
  3. produce empty elements in the results. This function serves to perform the matching of a pattern or a
  4. search and replace.//
  5.  
  6. function getTokens(rawString) {
  7. // NB: `.filter(Boolean)` removes any falsy items from an array //This will remove any null, 0, or Nan value from the array or string//
  8. return rawString.toLowerCase().split(/[ ,!.";:-]+/).filter(Boolean).sort(); // .sort function sorts array by alphabetical order//
  9. }
  10.  
  11. //The mostFrequentWord function assigns when called the getTokens array to the variable words.
  12. Below that is a new object for word frequency count called wordFrequencies. A for loop that will run and reference
  13. what "i" is which is the first text in the string that will return. They start at 0 not 1 and if the
  14. condition of less than or equal to words.length the value will be incremented and run immediately.
  15. //
  16.  
  17. function mostFrequentWord(text) {
  18. let words = getTokens(text);
  19. let wordFrequencies = {};
  20. for (let i = 0; i <= words.length; i++) {
  21. if (words[i] in wordFrequencies) {
  22. wordFrequencies[words[i]]++;
  23. } else {
  24. wordFrequencies[words[i]] = 1;
  25. }
  26. }
  27. let currentMaxKey = Object.keys(wordFrequencies)[0];
  28. let currentMaxCount = wordFrequencies[currentMaxKey];
  29.  
  30. for (let word in wordFrequencies) {
  31. if (wordFrequencies[word] > currentMaxCount) {
  32. currentMaxKey = word;
  33. currentMaxCount = wordFrequencies[word];
  34. }
  35. }
  36. return currentMaxKey;
  37. }
  38. // The script wil return the currentMaxKey and we will have the word used most.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement