-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathmap.ts
41 lines (37 loc) · 910 Bytes
/
map.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
import { Operator } from './types';
export function map<A, B>(f: (a: A) => B): Operator<A, B> {
return source => (_, sink) => {
source(0, (t, d) => {
sink(t, t === 1 ? f(d) : d);
});
};
}
export function scan<A, B>(
f: (accumulator: B, current: A) => B,
start?: B
): Operator<A, B> {
let hasAcc = arguments.length === 2;
return source => (_, sink) => {
let acc: any = start;
source(0, (t, d) => {
if (t === 0) {
sink(t, d);
if (hasAcc) sink(1, acc);
} else if (t === 1) {
if (hasAcc) acc = f(acc, d);
else {
hasAcc = true;
acc = d;
}
sink(1, acc);
} else sink(t, d);
});
};
}
export function debug<A>(msg: string | ((a: A) => void)): Operator<A, A> {
const f = typeof msg === 'function' ? msg : (x: A) => console.log(msg, x);
return map(x => {
f(x);
return x;
});
}