-
Notifications
You must be signed in to change notification settings - Fork 5
/
from.ts
63 lines (51 loc) · 1.11 KB
/
from.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import { Producer, END } from './types';
export function fromArray<T>(arr: Array<T>): Producer<T> {
return (_, sink) => {
let ended = false;
sink(0, (_: END) => {
ended = true;
});
for (let i = 0; i < arr.length; i++) {
if (ended) break;
sink(1, arr[i]);
}
if (!ended) sink(2);
};
}
export function fromPromise<T>(p: Promise<T>): Producer<T> {
return (_, sink) => {
let ended = false;
const resolve = (x: T) => {
if (ended) return;
sink(1, x);
if (ended) return;
sink(2);
};
const reject = (err = new Error()) => {
if (ended) return;
sink(2, err);
};
p.then(resolve, reject);
sink(0, (_: END) => {
ended = true;
});
};
}
export function from<T>(p: Promise<T> | Array<T>): Producer<T> {
if (Array.isArray(p)) {
return fromArray(p);
} else {
return fromPromise(p);
}
}
export function of<T>(x: T): Producer<T> {
return (_, sink) => {
let ended = false;
sink(0, (_: END) => {
ended = true;
});
if (ended) return;
sink(1, x);
if (!ended) sink(2);
};
}