Skip to content

Instantly share code, notes, and snippets.

@nash403
Last active January 14, 2025 03:29
Show Gist options
  • Save nash403/13f6973f126d46e506e3b23e878e160f to your computer and use it in GitHub Desktop.
Save nash403/13f6973f126d46e506e3b23e878e160f to your computer and use it in GitHub Desktop.
Vue 3 composable to create a reactive Map to use as an in memory (default) database. Extended with ability to standardize custom key generation.

useReactiveMap composable

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
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment