Skip to content

Instantly share code, notes, and snippets.

@t-davies
Last active February 18, 2019 16:54
Show Gist options
  • Save t-davies/7aa00cc4aea363e17adf8ff3c59d4072 to your computer and use it in GitHub Desktop.
Save t-davies/7aa00cc4aea363e17adf8ff3c59d4072 to your computer and use it in GitHub Desktop.
JavaScript word count, 5 mins kata
// task: count frequency of words in a string
// assumptions:
// - "words" are separated by spaces
// - input will always be a string, never undefined/null etc.
// - numbers and emoji are "words"
// - input will be latin script
// steps:
// - split input by ' '
// - loop through and add found instances to a map of word: count
// - if not found, add key else just add to value
// time complexity: O(n)
const text = '😍 this is an input, a really really nice input of more than 10 characters, and it has various words within it 😍';
const countWords = (input) => {
if (!input instanceof String) {
return [];
}
const counts = input.split(' ').reduce((count, word) => {
count.set(word, (count.get(word) || 0) + 1);
return count;
}, new Map());
return [...counts.entries()].sort((left, right) => right[1] - left[1]);
};
console.log(countWords(text));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment