SHARE
TWEET

Untitled

a guest Oct 23rd, 2019 73 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function getTokens(rawString) {
  2.   // NB: `.filter(Boolean)` removes any falsy items from an array
  3.   return rawString.toLowerCase().split(/[ ,!.";:-]+/).filter(Boolean).sort(); // Normalizes input through removing and seperating by spaces/punctuation. Makes it lowercase, sorts it in alphabetical order, and filters out any falsy entries. Finally returns an array of strings.
  4. }
  5.  
  6. function mostFrequentWord(text) {
  7.   let words = getTokens(text); // calls the getTokens function and sets words to the output
  8.   let wordFrequencies = {}; // Object declared outside of for loop to be used later
  9.   for (let i = 0; i <= words.length; i++) {
  10.     if (words[i] in wordFrequencies) { // if current array item is already entered in the object, then add +1 to the count
  11.       wordFrequencies[words[i]]++;
  12.     } else {
  13.       wordFrequencies[words[i]] = 1; // otherwise, make a new word entry and mark it as appearing once
  14.     }
  15.   }
  16.   /*
  17.   Currently, we should have an object that looks like this:
  18.  
  19.   wordFrequencies = {
  20.     hello: 3,
  21.     thanks: 1,
  22.     goodbye: 2
  23.   }
  24.   */
  25.   let currentMaxKey = Object.keys(wordFrequencies)[0]; // Sets first key to be considered the most frequently used word (however may not be the case)
  26.   let currentMaxCount = wordFrequencies[currentMaxKey]; // Gets the frequency of the word
  27.  
  28.   for (let word in wordFrequencies) { // For every word in wordFrequency, do this:
  29.     if (wordFrequencies[word] > currentMaxCount) { // If the word we're currently looking at has a larger frequency count than our previously set word, set it to the current one
  30.       currentMaxKey = word;
  31.       currentMaxCount = wordFrequencies[word];
  32.     }
  33.     // this happens all the way through the array until we get the final result: the most frequently used word
  34.   }
  35.   return currentMaxKey; // return the most frequently used word
  36. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top