Advertisement
Guest User

Untitled

a guest
Feb 23rd, 2019
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.70 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. function mostFrequentWord(text) {
  7. let words = getTokens(text);
  8. // As a string(text) is sent through the function mostFrequentWords it is first passed up through getTokens where it converts the string to lower case, runs it through a "regular expression" to sort the array into individual words, then runs it through.filter(boolean) which removes any falsy items (non letter characters? maybe?) from the array. It is then put back into the mostFrequentWord Function as the value "words".
  9. let wordFrequencies = {}; //let wordFrequencies sets up an empty object.
  10. for (let i = 0; i <= words.length; i++) { // a for loop is set up to iterate a counting function over the array of "words".
  11. if (words[i] in wordFrequencies) {
  12. wordFrequencies[words[i]]++; // if a word is counted more than once then it will continue to be counted or...
  13. } else {
  14. wordFrequencies[words[i]] = 1; // it will be only counted once.
  15. }
  16. }
  17. let currentMaxKey = Object.keys(wordFrequencies)[0]; // I think it's setting currentMaxKey to the wordFrequency array?
  18. let currentMaxCount = wordFrequencies[currentMaxKey]; // Unsure?
  19.  
  20. for (let word in wordFrequencies) { // for loop set up to start counting of most frequent word?
  21. if (wordFrequencies[word] > currentMaxCount) {
  22. currentMaxKey = word;
  23. currentMaxCount = wordFrequencies[word];
  24. }// if- the wordFrquencies(current word being counted) is greater than the currentMaxCount then it becomes the new currentMaxKey.
  25. }
  26. return currentMaxKey; // returns the value of currentMaxKey
  27. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement