| 7 | * @public |
| 8 | */ |
| 9 | export class AtomMap<K, V> implements Map<K, V> { |
| 10 | private atoms: Atom<ImmutableMap<K, Atom<V | UNINITIALIZED>>> |
| 11 | |
| 12 | /** |
| 13 | * Creates a new AtomMap instance. |
| 14 | * |
| 15 | * name - A unique name for this map, used for atom identification |
| 16 | * entries - Optional initial entries to populate the map with |
| 17 | * @example |
| 18 | * ```ts |
| 19 | * // Create an empty map |
| 20 | * const map = new AtomMap('userMap') |
| 21 | * |
| 22 | * // Create a map with initial data |
| 23 | * const initialData: [string, number][] = [['a', 1], ['b', 2]] |
| 24 | * const mapWithData = new AtomMap('numbersMap', initialData) |
| 25 | * ``` |
| 26 | */ |
| 27 | constructor( |
| 28 | private readonly name: string, |
| 29 | entries?: Iterable<readonly [K, V]> |
| 30 | ) { |
| 31 | let atoms = emptyMap<K, Atom<V>>() |
| 32 | if (entries) { |
| 33 | atoms = atoms.withMutations((atoms) => { |
| 34 | for (const [k, v] of entries) { |
| 35 | atoms.set(k, atom(`${name}:${String(k)}`, v)) |
| 36 | } |
| 37 | }) |
| 38 | } |
| 39 | this.atoms = atom(`${name}:atoms`, atoms) |
| 40 | } |
| 41 | |
| 42 | /** |
| 43 | * Retrieves the underlying atom for a given key. |
| 44 | * |
| 45 | * @param key - The key to retrieve the atom for |
| 46 | * @returns The atom containing the value, or undefined if the key doesn't exist |
| 47 | * @internal |
| 48 | */ |
| 49 | getAtom(key: K): Atom<V | UNINITIALIZED> | undefined { |
| 50 | const valueAtom = this.atoms.__unsafe__getWithoutCapture().get(key) |
| 51 | if (!valueAtom) { |
| 52 | // if the value is missing, we want to track whether it's in the present keys set |
| 53 | this.atoms.get() |
| 54 | return undefined |
| 55 | } |
| 56 | return valueAtom |
| 57 | } |
| 58 | |
| 59 | /** |
| 60 | * Gets the value associated with a key. Returns undefined if the key doesn't exist. |
| 61 | * This method is reactive and will cause reactive contexts to update when the value changes. |
| 62 | * |
| 63 | * @param key - The key to retrieve the value for |
| 64 | * @returns The value associated with the key, or undefined if not found |
| 65 | * @example |
| 66 | * ```ts |
nothing calls this directly
no outgoing calls
no test coverage detected
searching dependent graphs…