Hemanth's Scribes

web

JavaScript MapReduce One Liner?!

Author Photo

Hemanth HM

Thumbnail

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})”

#javascript#linux
Author Photo

About Hemanth HM

Hemanth HM is a Sr. Machine Learning Manager at PayPal, Google Developer Expert, TC39 delegate, FOSS advocate, and community leader with a passion for programming, AI, and open-source contributions.