-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path03-tiny-store.ts
More file actions
45 lines (36 loc) · 1.13 KB
/
03-tiny-store.ts
File metadata and controls
45 lines (36 loc) · 1.13 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
// A simple signal, effect, memo, and computed library based on SolidJS.
let currentScope: () => void
export function createEffect(update: () => void) {
const parent = currentScope
currentScope = update
update()
currentScope = parent
}
export function createSignal<T>(): [() => T | undefined, (value: T) => void]
export function createSignal<T>(value: T): [() => T, (value: T) => void]
export function createSignal<T>(
value?: T,
): [() => T | undefined, (value: T) => void] {
const tracking = new Set<() => void>()
const get = () => {
if (currentScope) {
tracking.add(currentScope)
}
return value
}
const set = (val: T) => {
value = val
tracking.forEach((effect) => effect())
}
return [get, set]
}
export function createMemo<T>(compute: () => T) {
const [get, set] = createSignal<T>()
createEffect(() => set(compute()))
return get as () => T
}
export function createComputed<T>(value: T, compute: (oldValue: T) => T) {
const [get, set] = createSignal()
createEffect(() => set((value = compute(value))))
return get as () => T
}