-
Notifications
You must be signed in to change notification settings - Fork 0
/
core.ts
56 lines (49 loc) · 964 Bytes
/
core.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
type Context = () => void
let stack: Context[] = []
function getCurrentConext(): Context | undefined {
let context = stack[stack.length - 1]
return context
}
function create<T>(value: T) {
let listeners = new Set<() => void>()
function read(): T {
let context = getCurrentConext()
if (context) {
listeners.add(context)
}
return value
}
function write(newVal: T) {
value = newVal
listeners.forEach(fn => fn())
}
return {
get value(): T {
return read()
},
set value(val: T) {
write(val)
},
toString() {
return read()
},
valueOf() {
return read()
},
}
}
function run<T>(context: () => T) {
try {
stack.push(context)
return context()
} finally {
stack.pop()
}
}
function map<T>(fn: () => T) {
let s = create<T>(void 0 as any)
run(() => (s.value = fn()))
return s
}
export let S = Object.assign(create, { run, map })
export default S