Skip to content

Latest commit

 

History

History
34 lines (31 loc) · 1.04 KB

06_frequentword.org

File metadata and controls

34 lines (31 loc) · 1.04 KB

frequent word refactor

Refactor or provide a review for the following code. Or start over and solve the problem in a different way. Explain your choices.

function getTokens(rawString) {
  // NB: `.filter(Boolean)` removes any falsy items from an array
  return rawString.toLowerCase().split(/[ ,!.";:-]+/).filter(Boolean).sort();
}

function mostFrequentWord(text) {
  let words = getTokens(text);
  let wordFrequencies = {};
  for (let i = 0; i <= words.length; i++) {
    if (words[i] in wordFrequencies) {
      wordFrequencies[words[i]]++;
    } else {
      wordFrequencies[words[i]] = 1;
    }
  }
  let currentMaxKey = Object.keys(wordFrequencies)[0];
  let currentMaxCount = wordFrequencies[currentMaxKey];
  for (let word in wordFrequencies) {
    if (wordFrequencies[word] > currentMaxCount) {
      currentMaxKey = word;
      currentMaxCount = wordFrequencies[word];
    }
  }
  return currentMaxKey;
}

Originally posted by @Gianina Skarlett on Sep 19, 2018 in #javascript. They asked for help understanding the code.