documentcloud/underscore — Issue #452: still recommend flatMap or concatMap
Author: rebcabin
Created: 2012-01-30 02:41:42+00:00
State: open

with reference to issue 436, I agree that documenting the second argument to flatten is a good start, but it didn't quite close the issue for me. I would still recommend adding a "flatMap" or "concatMap" primitive to the base library so that we get proper chain composability. Adding this new primitive would not break anything, but would make chains of array-valued maps composable. For instance, imagine the following expression, in pseudo-C#, that represents the line items for high-value orders from a list of customers:
Customers
.Where(customer => customer.Orders
.SelectMany(order => order.LineItems)
.Sum() > 1000)
.SelectMany(customer => customer.Orders)
.SelectMany(order => order.LineItems) ;

to write this in underscore with a new flatMap primitive, the "SelectMany"s become "flatMaps."

I implemented a proposal for flatmap in a fork of underscore's source, along with a few unit tests for your consideration. I don't have docco running and I didn't produce a "min" version of the javascript, so it's just the javascript and the unit tests. https://github.com/rebcabin/underscore/commit/4f90bab75d8f69df8d8d0317354f9f5981e2fedb