First of all, I'm fairly new to streams, so I'm still getting to grips with some common patterns.
In many libraries we can split a stream into a stream of streams using .groupBy(keySelectorFn). For example, this stream is split into streams based on the value of 'a' in each object (pseudo-code, not based on any particular library):
var groups = Stream.of(
{ a: 1, b: 0 },
{ a: 1, b: 1 },
{ a: 2, b: 2 },
{ a: 1, b: 3 }
)
.groupBy(get('a'));
Say I want to process groups differently based on the value of 'a' of that group:
groups.map(function(group) {
if (..?) {
// Run the group through some process
}
return group;
});
I can't see how to get the value of 'a' without consuming the first element of each group (and if the first element of a group is consumed the group is no longer intact).
This seems to me a fairly common thing that I want to do with streams. Am I taking the wrong approach?
--- EDIT ---
Here's a more specific example of a problem that I'm stuck on:
var groups = Stream.of(
{ a: 1, b: 0 },
{ a: 1, b: 1 },
{ a: 2, b: 0 },
{ a: 2, b: 1 },
{ a: 2, b: 2 },
{ a: 1, b: 2 }
)
.groupBy(get('a'));
How to select the first 1 object where a === 1, and the first 2 objects where a === 2, and pass any other objects straight through? This seems logical to me:
groups.chain(function(group) {
return group.key === 1 ?
group.take(1) :
group.key === 2 ?
group.take(2) :
group ;
});
But group.key does not exist (and even if it did it would seem a bit... smelly).