-
Notifications
You must be signed in to change notification settings - Fork 6
/
scan.ts
48 lines (46 loc) · 1.11 KB
/
scan.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import {
Event,
EventStream,
EventStreamSeed,
isValue,
Observer,
Property,
PropertySeed,
valueEvent,
Scope,
} from "./abstractions"
import { applyScopeMaybe } from "./applyscope"
import { PropertySeedImpl } from "./property"
export function scan<A, B>(
initial: B,
fn: (state: B, next: A) => B,
scope: Scope
): (stream: EventStream<A> | EventStreamSeed<A>) => Property<B>
export function scan<A, B>(
initial: B,
fn: (state: B, next: A) => B
): (stream: EventStream<A> | EventStreamSeed<A>) => PropertySeed<B>
export function scan<A, B>(
initial: B,
fn: (state: B, next: A) => B,
scope?: Scope
): any {
return (seed: EventStream<A> | EventStreamSeed<A>) => {
const source = seed.consume()
let current = initial
return applyScopeMaybe(
new PropertySeedImpl(
[source, "scan", [fn]],
() => initial,
(onValue: Observer<B>, onEnd?: Observer<void>) => {
const unsub = source.subscribe((event) => {
current = fn(current, event)
onValue(current)
}, onEnd)
return unsub
}
),
scope
)
}
}