Guest User

Untitled

a guest
Nov 23rd, 2017
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.67 KB | None | 0 0
  1. // takes a string as input and returns an array of all words in the string, stripping non-alphanumeric characters
  2. function getTokens(rawString) {
  3. // NB: `.filter(Boolean)` removes any falsy items from an array
  4. return rawString.toLowerCase().split(/[ ,!.";:-]+/).filter(Boolean).sort();
  5. }
  6.  
  7. // takes in a string of text, and returns a string representation of the most frequently occuring word in that string
  8. function mostFrequentWord(text) {
  9. // assigns variable referring to array of words in string
  10. let words = getTokens(text);
  11. // declares an empty obj to store word counts
  12. let wordFrequencies = {};
  13. // iterates over words in array. for each word, if the word is present in the frequency object, the value is incremented; otherwise
  14. // it adds the word as a key with a value of 1
  15. for (let i = 0; i <= words.length; i++) {
  16. if (words[i] in wordFrequencies) {
  17. wordFrequencies[words[i]]++;
  18. } else {
  19. wordFrequencies[words[i]] = 1;
  20. }
  21. }
  22.  
  23. // declares variables to track the highest frequency word; intially set to the first key in the array of the frequency object's keys
  24. let currentMaxKey = Object.keys(wordFrequencies)[0];
  25. let currentMaxCount = wordFrequencies[currentMaxKey];
  26.  
  27. // iterates over keys in wordFrequencies object. if the value (count) of that key is greater than the current max, the key
  28. // replaces the currentMaxKey, and the value replaces the currentMaxCount
  29. for (let word in wordFrequencies) {
  30. if (wordFrequencies[word] > currentMaxCount) {
  31. currentMaxKey = word;
  32. currentMaxCount = wordFrequencies[word];
  33. }
  34. }
  35. // You wanted a word!? Well, here's a word! The most frequent word! The best word!
  36. return currentMaxKey;
  37. }
Add Comment
Please, Sign In to add comment