Created
March 25, 2024 10:44
-
-
Save TheLucifurry/68f7fff1bfad36b043cc87c24f169217 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { readonly, shallowReactive } from 'vue' | |
| import { useSet } from './useSet' | |
| interface IOptions<V> { | |
| merge?: (source: V, patch: Partial<V>) => V | |
| } | |
| function mergeSimple<V>(source: V, patch: Partial<V>): V { | |
| return { ...source, ...patch } | |
| } | |
| /** | |
| * Создает реактивный список объектов | |
| * Отличается от `useMap` возможностью частично обновлять объектные значения | |
| */ | |
| export function useRecords< | |
| K extends string | number | symbol, | |
| V extends Record<string, unknown> | |
| >(options: IOptions<V> = {}) { | |
| const keys = useSet<K>() | |
| const data = shallowReactive({}) as Record<K, V> | |
| const { | |
| merge = mergeSimple, | |
| } = options | |
| function get(key: K): V | undefined { | |
| return data[key] | |
| } | |
| function set(key: K, value: V) { | |
| keys.add(key) | |
| data[key] = value | |
| } | |
| function remove(key: K) { | |
| keys.delete(key) | |
| delete data[key] | |
| } | |
| function clear() { | |
| keys.forEach(k => remove(k as K)) | |
| keys.clear() | |
| } | |
| return { | |
| set, | |
| get, | |
| has: keys.has, | |
| update(key: K, value: Partial<V>) { | |
| set(key, merge(get(key) || {} as V, value)) | |
| }, | |
| delete: remove, | |
| clear, | |
| keys: readonly(keys), | |
| get size() { | |
| return keys.size | |
| }, | |
| } as const | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment