Created
February 13, 2014 15:31
-
-
Save hubgit/8977198 to your computer and use it in GitHub Desktop.
Count words of each length in a string of text
This file contains 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
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