Advertisement
Guest User

Untitled

a guest
May 24th, 2017
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.20 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. //this is saying we will use a function called mostFrequentWord that will have text as its only parameter
  8.  
  9. var words = getTokens(text);
  10. //now we are making a variable called words that will basically be the getTokens function
  11. //declared above(puts the strings to lowercase and sorts)
  12.  
  13. var wordFrequencies = {};
  14. //now, wordFrequencies is an object, but it is currently empty
  15.  
  16. for (var i = 0; i <= words.length; i++) {
  17. //this is a for loop. we are saying some variable (called i) will start at the 0 spot in an array - it will continue as
  18. //long as this is less than or equal to the length of the array - once we do the stuff below in the for loop, add 1
  19.  
  20. if (words[i] in wordFrequencies) {
  21. //this is the beginning of an if statement - it says if the i variable in the words array is in the wordFrequency object...
  22.  
  23. wordFrequencies[words[i]]++;
  24. }
  25. // (continued from prev line), then add 1 to wordFrequencies (to increase the counter)
  26.  
  27. else {
  28. wordFrequencies[words[i]]=1;
  29. }
  30. //if the previous statement is not true, then leave the word frequency to 1
  31. }
  32.  
  33. var currentMaxKey = Object.keys(wordFrequencies)[0];
  34. //this is an Object.key function. this is being used because you need to pair words (keys) to their wordFrequencies (values)
  35.  
  36. var currentMaxCount = wordFrequencies[currentMaxKey];
  37. //we created a currentMaxCount variable because eventually, we want this to hold the word with the highest frequency
  38.  
  39. for (var word in wordFrequencies) {
  40. //opening another for loop...
  41.  
  42. if (wordFrequencies[word] > currentMaxCount) {
  43. //part of the for loop.. if the wordFrequencies var that we made a loop for before is begger than the currentMaxCount just created...
  44.  
  45. currentMaxKey = word;
  46. //currentMaxKey then equals the word (basically, stop there)
  47.  
  48. currentMaxCount = wordFrequencies[word];
  49. //similar to line above
  50. }
  51. }
  52. return currentMaxKey;
  53. //the answer of the most frequently used word is now in this key, so return/display it
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement