Skip to content

Instantly share code, notes, and snippets.

@Osman8a
Created December 19, 2018 03:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Osman8a/5deb8a9af271778ee84c1304e3ce8da1 to your computer and use it in GitHub Desktop.
Save Osman8a/5deb8a9af271778ee84c1304e3ce8da1 to your computer and use it in GitHub Desktop.
Challenge: analyze a most frequent word program
function getTokens (rawString) {
  // NB: `.filter (Boolean)` removes any false items from an array
  return rawString.toLowerCase (). split (/ [,!. ";: -] + /). filter (Boolean) .sort ();
}
  
function mostFrequentWord (text) {
  // asgina a words the divided and organized string
  var words = getTokens (text);
  var wordFrequencies = {};
  // I walk the words vector
  for (var i = 0; i <= words.length; i ++) {
    // if the word in the position of the vector is inside the wordFrequencies object, I include it and add 1
    if (words [i] in wordFrequencies) {
      wordFrequencies [words [i]] ++;
    }
    else {
      wordFrequencies [words [i]] = 1;
    }
  }
 // get the wordFrequencies key
  var currentMaxKey = Object.keys (wordFrequencies) [0];
  var currentMaxCount = wordFrequencies [currentMaxKey];
  
  for (var word in wordFrequencies) {
    // if the word inside vector is greater than the current one then assign it
    // to the variable
    if (wordFrequencies [word]> currentMaxCount) {
      currentMaxKey = word;
      currentMaxCount = wordFrequencies [word];
    }
  }
  // returns the greatest
  return currentMaxKey;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment