-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathcoroutine.ts
More file actions
72 lines (65 loc) · 1.84 KB
/
coroutine.ts
File metadata and controls
72 lines (65 loc) · 1.84 KB
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
64
65
66
67
68
69
70
71
72
import { Priority } from "./contexts.ts";
import { DelimiterContext } from "./delimiter.ts";
import { ReducerContext } from "./reducer.ts";
import { Ok } from "./result.ts";
import type { Coroutine, Operation, Scope } from "./types.ts";
export interface CoroutineOptions<T> {
scope: Scope;
operation(): Operation<T>;
}
export function createCoroutine<T>(
{ operation, scope }: CoroutineOptions<T>,
): Coroutine<T> {
let reducer = scope.expect(ReducerContext);
let iterator: Coroutine<T>["data"]["iterator"] | undefined = undefined;
let routine = {
runLevel: 0,
scope,
data: {
get iterator() {
if (!iterator) {
iterator = operation()[Symbol.iterator]();
}
return iterator;
},
exit: (resolve) => resolve(Ok()),
},
next(result) {
routine.data.exit((exitResult) => {
routine.data.exit = (didExit) => didExit(Ok());
let validator = scope.get(DelimiterContext)?.validator ?? valid;
reducer.reduce([
scope.expect(Priority),
routine,
exitResult.ok ? result : exitResult,
validator,
"next",
]);
});
},
return(result) {
routine.data.exit((exitResult) => {
routine.data.exit = (didExit) => didExit(Ok());
let validator = scope.get(DelimiterContext)?.validator ?? valid;
reducer.reduce([
scope.expect(Priority),
routine,
exitResult.ok ? result : exitResult,
validator,
"return",
]);
});
},
} as Coroutine<T>;
return routine;
}
export function* useCoroutine(): Operation<Coroutine> {
return (yield {
description: "useCoroutine()",
enter: (resolve, routine) => {
resolve(Ok(routine));
return (uninstalled) => uninstalled(Ok());
},
}) as Coroutine;
}
const valid = () => true;