Why did they create a flatMap method? What is wrong with .map(...).flat()? Can they improve the performance by combining it that much?
If you're familiar with C#'s linq and it's reliance on SelectMany it's somewhat easier to see the significance.
In C#'s linq you might write something like:
from host in sources
from value in fetch_data_from(host)
select create_record(value, host)
with flatmap (and some abuse of notation) you can more easily implement this as: sources.flatmap( host => fetch_data_from(host)
.flatmap( value => create_record(value, host))
If you dig even further you'll find that what makes this powerful is that the flatMap, together with the function x => [x], turns arrays into a Monad. The separate functions map and flat also work, but this adds more conditions. Haskell folks tend to prefer flatMap because most of the conditions for a Monad can be encoded in its type signature (except [x].flatMap(x => x) == x, but that one is easy enough to check).You'll find equivalents in all the JS utility libraries and most functional programming language standard libraries (and languages like Ruby with functional-ish subsets), so there's a lot of evidence that people who write code in that style like to have such a function available.
I personally feel flatMap is a much more used method than flat, so if you want to remove one, I would remove flat.
Flat can flatten any level of nesting (it just defaults to 1), so would be difficult to implement in terms of flatMap.
function flatten(x, n=1) {
return n > 0 ? x.flatmap(y => flatten(y, n-1))
: x;
}Why is flatMap = map().flat() and not flat().map()
flatmap = flat ∘ map