Skip to content

Instantly share code, notes, and snippets.

@hubgit
Created February 13, 2014 15:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hubgit/8977198 to your computer and use it in GitHub Desktop.
Save hubgit/8977198 to your computer and use it in GitHub Desktop.
Count words of each length in a string of text
var pluralise = function(count, single, plural) {
return String(count) + ' ' + (count === 1 ? single : plural);
}
// zero-fill an array of 20 items
var input = Array.apply(null, new Array(20)).map(Number.prototype.valueOf, 0);
// match words
p.match(/\b(\w+)\b/g).map(function(word) {
// get the length of each word
return word.length;
}).reduce(function(counts, letters) {
// increment the counter for the word length
counts[letters]++;
return counts;
}, input).map(function(count, letters) {
// generate text
return pluralise(count, 'word', 'words') + ' with ' + pluralise(letters, 'letter', 'letters')
}).join('\n')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment