Vue 3 composable to create a reactive Map to use as a small local database.
In memory by default, users can pass a custom map object to override that behavior.
The returned reactive Map is extended with ability to standardize custom key generation.
| function useReactiveMap(initialValues, options = { shallow: true }) { | |
| function isUsableAsMapKey(value) { | |
| const type = typeof value | |
| return ( | |
| value != null && | |
| (type === 'string' || | |
| type === 'number' || | |
| type === 'boolean' || | |
| type === 'symbol' || | |
| type === 'bigint') | |
| ); | |
| } | |
| const generateKey = (...args) => options?.getKey | |
| ? options.getKey(...args) | |
| // Default key: Serialize args | |
| : args.length === 1 && isUsableAsMapKey(args[0]) ? args[0] : JSON.stringify(args) | |
| const initMap = () => { | |
| // TODO: find out how to use Proxy to extend the Map ability to directly use generateKey instead of having to call from outside this composable | |
| return (options?.shallow ? shallowReactive : reactive)(options?.map ? options.map : new Map(initialValues || [])) | |
| } | |
| const data = initMap() | |
| Object.assign(data, { generateKey }) // add ability to standardize custom key generation | |
| return data | |
| } |