Skip to content

Instantly share code, notes, and snippets.

@offero
Forked from oscarmorrison/countWordsInText.js
Last active January 14, 2017 20:58
Show Gist options
  • Save offero/0b816e5829d06402300d89a3bc3dd420 to your computer and use it in GitHub Desktop.
Save offero/0b816e5829d06402300d89a3bc3dd420 to your computer and use it in GitHub Desktop.
count the words in a string, and order by popularity
function countWordsInText(text) {
let count = {};
let popularity = []; // maybe this should be an object due to JS array expansion logic
function updateWord(word, ct) {
if (popularity[ct-1]) {
popularity[ct-1].delete(word);
}
if (!popularity[ct]) {
popularity[ct] = new Set();
}
popularity[ct].add(word);
}
for(let word of text.split(' ')) {
word = word.replace(/[^a-zA-Z]/g, '').toLowerCase();
let ct = count[word] = (count[word] || 0) + 1;
updateWord(word, ct);
}
return popularity;
}
function printSortedWordsAndCounts(popularity) {
for(let i = popularity.length; i > 0; i--) {
if(popularity[i] && popularity[i].size) {
console.log(i, popularity[i]);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment