Last active
August 12, 2021 03:50
-
-
Save pdnguyen/274f5b5bbaea064dbd837f7441627830 to your computer and use it in GitHub Desktop.
wordfrequencies
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 wordFrequencies(s) { | |
| let wordFrequencies = new Map(); | |
| let words = s.split(' '); | |
| for (let i = 0; i < words.length; i++) { | |
| // word for our purposes contains letters, numbers, or a hyphen (no other punctuation) | |
| const word = words[i].toLowerCase().match(/([a-z0-9-]+)/)[0]; | |
| if (wordFrequencies.has(word)) { | |
| wordFrequencies.set(word, parseInt(wordFrequencies.get(word)) + 1); | |
| } else { | |
| wordFrequencies.set(word, 1); | |
| } | |
| } | |
| return [...wordFrequencies.entries()].sort((a, b) => { | |
| if (a[0] > b[0]) { | |
| return 1; | |
| } | |
| if (a[0] < b[0]) { | |
| return -1 | |
| } | |
| return 0; | |
| }); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment