JavaScript MapReduce One liner?!

After Word frequency using mapreduce in python
I got my paws dirty with some silly javascript, after reducing a whole chuck of code, it turned out to be a simple one liner in JavaScript.
A linear implementation of map reduce, none the less it was fun and indeed will be much useful if on node.js.

Enough of talking! The below is the one liner that would give the word frequency in JSON format.

One Liner :

String.prototype.map_reduce = function(){return this.toLowerCase().split(/\W+/g).reduce(function (t, w) { if (w) t[w] = (t[w] || 0) + 1; return t; }, {}).toSource()}

Prettier version :

String.prototype.map_reduce = function () {
return this.toLowerCase().
split(/\W+/g).
reduce(function (t, w) {
if (w) {
t[w] = (t[w] || 0) + 1;
}
return t;
}, {}).
toSource()
}

Example :

>>> "The quick brown fox jumped over the lazy".map_reduce()

>>> "({the:2, quick:1, brown:1, fox:1, jumped:1, over:1, lazy:1, dog:1})"

Share this