-
Notifications
You must be signed in to change notification settings - Fork 2
/
svelte-stores.ts
68 lines (52 loc) · 1.51 KB
/
svelte-stores.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
64
65
66
67
68
// An implementation of Svelte stores. #rewrite
export type StopFunction = () => void
export type Subscriber<T> = (value: T) => void
export type UpdateFunction<T> = (value: T) => T
export type Executor<T> = (update: (value: T) => void) => void
export interface Store<T> {
set?(value: T): void
subscribe(onUpdate: Subscriber<T>): StopFunction
}
export interface Readable<T> extends Exclude<Store<T>, "set"> {}
export interface Writable<T> extends Store<T> {
set(value: T): void
}
export interface AsyncWritable<T> extends Store<T> {
set(value: T | PromiseLike<T>): void
}
export function writable<T>(value: T): Writable<T> {
const listeners = new Set<Subscriber<T>>()
return {
set(v) {
value = v
listeners.forEach((fn) => fn(value))
},
subscribe(onUpdate) {
listeners.add(onUpdate)
onUpdate(value)
return () => listeners.delete(onUpdate)
},
}
}
export function readable<T>(value: T, executor: Executor<T>): Store<T> {
const { set, subscribe } = writable<T>(value)
executor(set)
return { subscribe }
}
export function asyncWritable<T>(value: T): AsyncWritable<T> {
const { set, subscribe } = writable<T>(value)
let asyncId = 0
return {
subscribe,
async set(value) {
const id = ++asyncId
const result = await value
if (asyncId === id) set(result)
},
}
}
export function asyncReadable<T>(value: T, executor: Executor<Promise<T>>) {
const { set, subscribe } = asyncWritable<T>(value)
executor(set)
return { subscribe }
}