caolan / caolan/highland

Branching a Stream

Open
#90 8 comments 0 reactions 0 assignees View on GitHub
enhancement greenspunning
Dominant language
JavaScript
Stars
3.4k
Forks
145
PR merge metrics
No merged PRs in 30d

Description

What do you think about a `Stream.branch` function? One that would split a stream into two streams by applying a filter function. It could return a stream of two streams with shared backpressure: one with the filtered values and the other one with the rejected values. It could take two optional transform functions, which will applied as through streams to the result streams.

To explain what I mean a naive polyfill implementation:

``` js
var stream = _([0,1,2,3,4,5]);

// Branch a stream into two streams by applying a filter.
// Optionally apply through streams to the result streams.
// Returns a Stream of two streams: one with the filtered and
// another one with the rejected values.
stream.branch = function(filter, filteredTransform, rejectedTransform) {
var filtered = this.fork().filter(filter);
var rejected = this.fork().reject(filter);

if (filteredTransform) {
filtered = filtered.through(filteredTransform);
}
if (rejectedTransform) {
rejected = rejected.through(rejectedTransform);
}

return _([filtered, rejected]);
};
```

You can then use it like this:

``` js
// filter
function isEven(n) {
return n % 2 === 0;
}
// filtered stream transform
function ft(source) {
return source
.map(function(n) {
return '' + n + ' (even)';
});
};

// branch and merge
stream.branch(isEven, ft).merge().each(_.log);
```

Please excuse me if this is a dump question. I repeatedly found myself writing such a pattern when I wanted to take a stream and apply some calculations on a subset of values but want to retain both the computed and untouched values in the result stream.

Do you think this is beneficial at all?
Should the function return a single stream, already merged both streams?
Should it work with multiple branches?
Is the name too general? What about `tee`?

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.