-
Notifications
You must be signed in to change notification settings - Fork 2
/
scan.ts
35 lines (30 loc) · 851 Bytes
/
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
import { Operator, Observer } from '../index';
import { createSource } from '../sources';
import subscribe from '../utils/subscribe';
type Reduce<I, O> = (acc: O, value: I) => O;
/**
* Applies an accumulator function over the source, and emits each intermediate result
*
* @param reducer - reducer function called on each source value
* @param seed - initial accumulation value
* @return callbag operator
*
* @public
*/
function scan<I, O>(reducer: Reduce<I, O>, seed: O): Operator<I, O> {
return source => {
return createSource((next, complete, error) => {
let acc = seed;
const observer: Observer<I> = {
next: value => {
acc = reducer(acc, value);
next(acc);
},
error,
complete,
};
return subscribe(source)(observer);
});
};
}
export default scan;