deno.land / x / jotai@v1.8.4 / src / utils / weakCache.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 type { Atom } from 'jotai'
type WeakCache<T> = WeakMap<object, [WeakCache<T>] | [WeakCache<T>, T]>
const getWeakCacheItem = <T>( cache: WeakCache<T>, deps: readonly object[]): T | undefined => { do { const [dep, ...rest] = deps const entry = cache.get(dep as object) if (!entry) { return } if (!rest.length) { return entry[1] } cache = entry[0] deps = rest } while (deps.length)}
const setWeakCacheItem = <T>( cache: WeakCache<T>, deps: readonly object[], item: T): void => { do { const [dep, ...rest] = deps let entry = cache.get(dep as object) if (!entry) { entry = [new WeakMap()] cache.set(dep as object, entry) } if (!rest.length) { entry[1] = item return } cache = entry[0] deps = rest } while (deps.length)}
export const createMemoizeAtom = () => { const cache: WeakCache<Atom<unknown>> = new WeakMap() const memoizeAtom = < AtomType extends Atom<unknown>, Deps extends readonly object[] >( createAtom: () => AtomType, deps: Deps ) => { const cachedAtom = getWeakCacheItem(cache, deps) if (cachedAtom) { return cachedAtom as AtomType } const createdAtom = createAtom() setWeakCacheItem(cache, deps, createdAtom) return createdAtom } return memoizeAtom}
jotai

Version Info

Tagged at
2 years ago