Skip to content

Instantly share code, notes, and snippets.

@codyromano
Last active February 21, 2017 18:41
Show Gist options
  • Select an option

  • Save codyromano/0758bd3e524d71b72564e68cfc3fd205 to your computer and use it in GitHub Desktop.

Select an option

Save codyromano/0758bd3e524d71b72564e68cfc3fd205 to your computer and use it in GitHub Desktop.
/**
* @desc Find the k most frequently occurring words in a body of text.
*
* @param {String} paragraph
* @param {Integer} k
* @returns {Array}
*/
function getMostFrequentWords(paragraph = '', k = 0) {
if (typeof paragraph !== 'string' || !Number.isInteger(k) || k < 0) {
throw new TypeError('Invalid paragraph text or frequency count.');
}
if (k === 0) {
// Go home; you're drunk.
return [];
}
// Make the search case-insensitive
const words = paragraph.split(' ').map((word) => word.toLowerCase());
// Map each word to the frequency of its appearance
// E.g. {"dog": 2, "fish": 3}
const frequencyMap = words.reduce((map, string) => {
map[string] = Number.isInteger(map[string]) ? ++map[string] : 1;
return map;
}, {});
// Frequency of the word that appears most often
const maxFrequency = Math.max(...Object.values(frequencyMap));
/* Construct an array where each index corresponds to the frequency
of a word. Continuing the example above, "dog" would go at index 2;
"fish" would go at index 3, etc. */
let frequencyArray = new Array(maxFrequency);
for (const string in frequencyMap) {
const frequency = frequencyMap[string];
// Use an array to account for words that occur in the same frequency
let wordsWithFreq = (frequencyArray[frequency] || []);
frequencyArray[frequency] = wordsWithFreq.concat(string);
}
// Iterate through the frequency array in reverse
let index = maxFrequency;
let result = [];
while (index > 1 && k > 0) {
// We check each value to see if it's an array because some values
// may be undefined.
const words = frequencyArray[index];
if (Array.isArray(words)) {
const maxWordsAddable = Math.min(k, words.length);
result = result.concat( words.slice(0, maxWordsAddable) );
// Subtract these words from the total number of words requested
k-= maxWordsAddable;
}
--index;
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment