deno.land / x / jotai@v1.8.4 / src / utils / atomFamily.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
69
70
71
72
73
74
import type { Atom } from 'jotai'
type ShouldRemove<Param> = (createdAt: number, param: Param) => boolean
export interface AtomFamily<Param, AtomType> { (param: Param): AtomType remove(param: Param): void setShouldRemove(shouldRemove: ShouldRemove<Param> | null): void}
export function atomFamily<Param, AtomType extends Atom<unknown>>( initializeAtom: (param: Param) => AtomType, areEqual?: (a: Param, b: Param) => boolean): AtomFamily<Param, AtomType>
export function atomFamily<Param, AtomType extends Atom<unknown>>( initializeAtom: (param: Param) => AtomType, areEqual?: (a: Param, b: Param) => boolean) { type CreatedAt = number // in milliseconds let shouldRemove: ShouldRemove<Param> | null = null const atoms: Map<Param, [AtomType, CreatedAt]> = new Map() const createAtom = (param: Param) => { let item: [AtomType, CreatedAt] | undefined if (areEqual === undefined) { item = atoms.get(param) } else { // Custom comparator, iterate over all elements for (const [key, value] of atoms) { if (areEqual(key, param)) { item = value break } } }
if (item !== undefined) { if (shouldRemove?.(item[1], param)) { createAtom.remove(param) } else { return item[0] } }
const newAtom = initializeAtom(param) atoms.set(param, [newAtom, Date.now()]) return newAtom }
createAtom.remove = (param: Param) => { if (areEqual === undefined) { atoms.delete(param) } else { for (const [key] of atoms) { if (areEqual(key, param)) { atoms.delete(key) break } } } }
createAtom.setShouldRemove = (fn: ShouldRemove<Param> | null) => { shouldRemove = fn if (!shouldRemove) return for (const [key, value] of atoms) { if (shouldRemove(value[1], key)) { atoms.delete(key) } } } return createAtom}
jotai

Version Info

Tagged at
2 years ago