I’m trying to understand why the author of this function would call reduce on an object that is already the result of a call to map. This is a render function from a backbone app (demo here http://fire-camp.heroku.com/ ). The variable “messages” represents a collection of the messages the users enter into the messaging system. Why would the author call map and then reduce on the results of map i.e. ‘data.’ I don’t understand how reduce adds anything new to the data variable. Let me know if you need more information.
render: function() {
var data = messages.map(function(message) { return message.get('content') + 'n'});
var result = data.reduce(function(memo,str) { return memo + str }, '');
$("#chatHistory").text(result);
return this;
}
Full source code for the very short app is here but I don’t think you’ll need it. https://github.com/ryandotsmith/fire-camp
As @Pointy mentioned, the reason the author has used
reduceis to concatenate the array into a single string (or reducing
it to a string). As @Pointy also mentions, though, the rationale
for using
reduceis not very good in this case.Given the code on GitHub there are several alternatives that
are better. Considering that the code uses Backbone.js and that
the
messagesvariable points to aBackbone.Collectionthiscode would be more clear if it read something along the lines
of this:
Using
reducefor joining an array of strings is overkill andobscures the intention of the code. Using
maptogether withBackbone.Collectionjust to pluck out a particular attributefrom the models inside also somewhat obscures the intention
of the code.