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.

Revisions

  1. nash403 revised this gist Jan 14, 2025. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion useReactiveMap.js
    Original file line number Diff line number Diff line change
    @@ -23,7 +23,7 @@ function useReactiveMap(initialValues, options = { shallow: true }) {

    const data = initMap()

    Object.assign(db, { generateKey }) // add ability to standardize custom key generation
    Object.assign(data, { generateKey }) // add ability to standardize custom key generation

    return data
    }
  2. nash403 created this gist Jan 9, 2025.
    7 changes: 7 additions & 0 deletions Readme.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,7 @@
    # `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.
    29 changes: 29 additions & 0 deletions useReactiveMap.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,29 @@
    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(db, { generateKey }) // add ability to standardize custom key generation

    return data
    }