scottfontenot
7/10/2017 - 1:32 AM

Unit 2-Lesson 6: Challenge: analyze a most frequent word program

Unit 2-Lesson 6: Challenge: analyze a most frequent word program

function getTokens(rawString) {
  /*
    a function above that takes a parameter `rawString` and returns same parameter: converts to lower case, splits convert to     an array, filters out all falsy values, and sorts values using the .sort() method
  */
  return rawString.toLowerCase().split(/[ ,!.";:-]+/).filter(Boolean).sort();
}
  
function mostFrequentWord(text) {
  /* 
     define a function that takes `text` as parameter, creates variable 'words' to be a an array of 
     letters inside `text`.
  */
  const words = getTokens(text);
  /*
    create an empty object called `wordFrequencies` to track `words` for frequent occurrances of each word 
    and how many times does a particular word appears.
  */
  
  const wordFrequencies = {};
  /*
    create a for loop to determine how many value are in `words`.
  */
  for (let i = 0; i <= words.length; i++) {
    /* 
      increment any `words` that appears and track the count for `words` on the if statement.
    */
    if (words[i] in wordFrequencies) {
      wordFrequencies[words[i]]++;
    }
    /*
      if there are no `words` that appears, then set the count for any `words` to always be one. Create a property
      so it'll always equal one on the else statment.
    */
    else {
      wordFrequencies[words[i]]=1;
    }
  }
  /* 
    define a variable that calls on our object. The first key within the object starts at zero. 
  */
  let currentMaxKey = Object.keys(wordFrequencies)[0];
  /*
    define a variable so it calls on that object and it's key. This local variable will be used
    to track the max word count.
  */
  let currentMaxCount = wordFrequencies[currentMaxKey];
  /* 
    create a FOR loop to check the reoccurance for each word. 
  */
  for (var word in wordFrequencies) {
    /*
      check if the appearance of a particular word's value is greater than our currentMaxCount.
    */
    if (wordFrequencies[word] > currentMaxCount) {
    /*
       update the max value. It will show what the word is and number of times it has appeared. Otherwise, it will move
        to the next iteration and start the process over.
    */
      currentMaxKey = word;
      currentMaxCount = wordFrequencies[word];
    }
  }
  /*
    currentMaxKey function to return a max count for every word that has repeatedly appeared in the first
    function `getTokens`..this was converted from a string to a array in order to break it down into values to build
    out our second function.
  */
  
  return currentMaxKey;
}