Last active
August 29, 2015 14:20
-
-
Save erikdonohoo/1f8e809f1c9681ef2770 to your computer and use it in GitHub Desktop.
Count words in file, order by highest count, limit by passed parameter
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 word = /\b[a-zA-Z][a-zA-Z0-9\-']*\b/g; | |
var words = {}; | |
var fs = require('fs'); | |
var path = require('path'); | |
function convert(str, amount) { | |
str = fs.readFileSync(path.join(__dirname, str), 'utf8'); | |
while ((match = word.exec(str))) { | |
var w = match[0].toLowerCase(); | |
words[w] = words[w] ? words[w] + 1 : 1; | |
} | |
var list = []; | |
for (var found in words) { | |
list[words[found]] = list[words[found]] || []; | |
list[words[found]].push({'word': found, value: words[found]}); | |
} | |
return list.filter(function (l) { | |
return l != null; | |
}).reduce(function (prev, cur) { | |
return prev.concat(cur); | |
},[]).slice(amount * -1).reverse(); | |
} | |
console.log(convert(process.argv[2], process.argv[3])); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment