lazy.js
lazy.js copied to clipboard
Feature request: concatMap
It’s a pretty common pattern to map a sequence to a sequence of sequences, and then flatten the result back to a sequence:
var words = Lazy(["cowbell", "zebra"]);
var letters = words
.map(function (word) { return word.split(""); })
.flatten();
(Although it would be better if flatten was non-recursive, see #125).
concatMap just combines these into a single operation:
var words = Lazy(["cowbell", "zebra"]);
var letters = words.concatMap(function (word) { return word.split(""); });
Why bother combining them into a single function when you can just chain them? Well, my request is motivated by the fact that I’m using TypeScript. Provided that the flatten is non-recursive, concatMap can be strictly typed, but flatten can’t:
interface Sequence<T> {
concatMap<U>(f: T => Sequence<U>): Sequence<U>;
flatten(): Sequence<any>; // Can't determine the type of the result
// ...
}
I’m not sure if TypeScript is something you care about, but if you do then introducing concatMap would be a significant improvement.
Having this exact problem now. I'm using TypeScript and trying to flatten arrays, but it's not registering with TypeScript, so map+flatten from Lazy.js is unusable.