Guest User

Untitled

a guest
May 23rd, 2018
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.87 KB | None | 0 0
  1. function getTokens(rawString) {
  2. // NB: `.filter(Boolean)` removes any falsy items from an array
  3. // we receive a string, .toLowerCase makes it all toLowerCase
  4. // split() returns an array of strings seporated on what we passed into it. so breaking it up into words
  5. // finally .sort() sorts alphabetically
  6. return rawString.toLowerCase().split(/[ ,!.";:-]+/).filter(Boolean).sort();
  7. }
  8.  
  9. //
  10. function mostFrequentWord(text) { // pass in a string variable
  11. let words = getTokens(text); // send string variable to the getTokens function and recieve an array of words, this array is sorted alphabetically
  12. let wordFrequencies = {}; // Create an object with no properties
  13. for (let i = 0; i <= words.length; i++) { // Loop through our array
  14. if (words[i] in wordFrequencies) { // if the word is already a key in our object
  15. wordFrequencies[words[i]]++; // then increment the value
  16. } else { // if it isn't already a key in our object
  17. wordFrequencies[words[i]] = 1; // then create it and set its value to 1
  18. }
  19. }
  20. let currentMaxKey = Object.keys(wordFrequencies)[0]; // create a variable and assign the name of the first key (or word) to it
  21. let currentMaxCount = wordFrequencies[currentMaxKey]; // create a variable and assign the value of that first key to it
  22.  
  23. for (let word in wordFrequencies) { // loop through the object
  24. if (wordFrequencies[word] > currentMaxCount) { // if the value is higher than the current max
  25. currentMaxKey = word; // reset the highest variables to these values
  26. currentMaxCount = wordFrequencies[word];
  27. }
  28. }
  29. return currentMaxKey; // return the name of the key that has the highest value. In other words . . . the word that shows up the most in the paragraph sent to us.
  30. }
Add Comment
Please, Sign In to add comment