-
-
Notifications
You must be signed in to change notification settings - Fork 144
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(rstream): re-implement bisect() using PubSub, update tests
- Loading branch information
1 parent
cbc600e
commit 846aaf9
Showing
2 changed files
with
48 additions
and
23 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,17 +1,41 @@ | ||
import { Predicate } from "@thi.ng/api/api"; | ||
|
||
import { ISubscriber } from "../api"; | ||
import { Subscription } from "../subscription"; | ||
import { PubSub } from "../pubsub"; | ||
|
||
export function bisect<T>(pred: Predicate<T>, a?: ISubscriber<T>, b?: ISubscriber<T>) { | ||
return new Subscription<T, T>({ | ||
next(x) { | ||
const sub = pred(x) ? a : b; | ||
sub.next && sub.next(x); | ||
}, | ||
done() { | ||
a.done && a.done(); | ||
b.done && b.done(); | ||
} | ||
}); | ||
/** | ||
* Returns a new `PubSub` instance using given predicate `pred` as | ||
* boolean topic function and `a` & `b` as subscribers for truthy (`a`) | ||
* and falsey `b` values. | ||
* | ||
* ``` | ||
* rs.fromIterable([1,2,3,4]).subscribe( | ||
* rs.bisect( | ||
* (x) => !(x & 1), | ||
* { next: (x) => console.log("even", x) }, | ||
* { next: (x) => console.log("odd", x) } | ||
* ) | ||
* ); | ||
* ``` | ||
* | ||
* If `a` or `b` need to be subscribed to directly, then `a` / `b` MUST | ||
* be converted into a `Subscription` instance (if not already) and a | ||
* reference kept prior to calling `bisect()`. | ||
* | ||
* ``` | ||
* const even = new rs.Subscription({next: (x) => console.log("even", x) }); | ||
* const odd = new rs.Subscription({next: (x) => console.log("odd", x) }); | ||
* | ||
* rs.fromIterable([1,2,3,4]).subscribe(rs.bisect((x) => !(x & 1), even, odd)); | ||
* ``` | ||
* | ||
* @param pred | ||
* @param a | ||
* @param b | ||
*/ | ||
export function bisect<T>(pred: Predicate<T>, a?: ISubscriber<T>, b?: ISubscriber<T>): PubSub<T, T> { | ||
const sub = new PubSub<T, T>({ topic: pred }); | ||
sub.subscribeTopic(true, a); | ||
sub.subscribeTopic(false, b); | ||
return sub; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters