Over a million developers have joined DZone.

A JavaScript MapReduce One-Liner

· Big Data Zone

Read this eGuide to discover the fundamental differences between iPaaS and dPaaS and how the innovative approach of dPaaS gets to the heart of today’s most pressing integration problems, brought to you in partnership with Liaison.

After my post on "Word frequency using MapReduce in Python," I got my paws dirty with some silly Javascript. Once I reduced a whole chunk of code, it turned out to be a simple one-liner in JavaScript. A linear implementation of MapReduce, but it was fun and indeed will be useful if on node.js.

Enough talking! Below is the one liner that will 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()}

The 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})"

 

Discover the unprecedented possibilities and challenges, created by today’s fast paced data climate and why your current integration solution is not enough, brought to you in partnership with Liaison

Topics:

Published at DZone with permission of Hemanth HM, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}