WordCount

by Larry Adams

JavaScript

function Counter() {
    this.values = {};
    this.add = function(value) {
        this.values[value] = (this.values[value]||0) + 1;
        return this.values[value];
    }
}
function wc(words, caseInsensitive) {
    var c = new Counter;
    words.split(' ').forEach(function(n){
        c.add(caseInsensitive? n.toLocaleLowerCase(): n);
    });
    return c.values;
}
Object.toDoubles = function(obj, valuesFirst) {
    var doubles = [], i;
    for(i in obj) if(obj.hasOwnProperty(i)) {
        doubles.push(valuesFirst?[obj[i], i]:[i, obj[i]]);
    }
    return doubles;
};
Object.compare = function(a, b) {
    return a < b? -1: a > b? 1: 0;
}
Array.sortByKey = function(key, reverse) {
    return function(a, b){
        return Object.compare(a[key], b[key])*(reverse?-1:1);
    };
};
console.log(Object.toDoubles(wc("The quick brown fox jumped over the lazy dog.", true),true).sort(Array.sortByKey(0, true)).map(function(n){return n.join(': ');}));