-
-
Save offero/0b816e5829d06402300d89a3bc3dd420 to your computer and use it in GitHub Desktop.
count the words in a string, and order by popularity
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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