UNPKG

@tldraw/utils

Version:

tldraw infinite canvas SDK (private utilities).

8 lines (7 loc) 2.77 kB
{ "version": 3, "sources": ["../../src/lib/cache.ts"], "sourcesContent": ["/**\n * A lightweight cache implementation using WeakMap for storing key-value pairs.\n *\n * A micro cache that stores computed values associated with object keys.\n * Uses WeakMap internally, which means keys can be garbage collected when no other\n * references exist, and only object keys are supported. Provides lazy computation\n * with memoization.\n *\n * @example\n * ```ts\n * const cache = new WeakCache<User, string>()\n * const user = { id: 1, name: 'Alice' }\n *\n * // Get cached value, computing it if not present\n * const displayName = cache.get(user, (u) => `${u.name} (#${u.id})`)\n * // Returns 'Alice (#1)'\n *\n * // Subsequent calls return cached value\n * const sameName = cache.get(user, (u) => `${u.name} (#${u.id})`)\n * // Returns 'Alice (#1)' without recomputing\n * ```\n * @public\n */\nexport class WeakCache<K extends object, V> {\n\t/**\n\t * The internal WeakMap storage for cached key-value pairs.\n\t *\n\t * @public\n\t */\n\titems = new WeakMap<K, V>()\n\n\t/**\n\t * Get the cached value for a given key, computing it if not already cached.\n\t *\n\t * Retrieves the cached value associated with the given key. If no cached\n\t * value exists, calls the provided callback function to compute the value, stores it\n\t * in the cache, and returns it. Subsequent calls with the same key will return the\n\t * cached value without recomputation.\n\t *\n\t * @param item - The object key to retrieve the cached value for\n\t * @param cb - Callback function that computes the value when not already cached\n\t * @returns The cached value if it exists, otherwise the newly computed value from the callback\n\t *\n\t * @example\n\t * ```ts\n\t * const cache = new WeakCache<HTMLElement, DOMRect>()\n\t * const element = document.getElementById('my-element')!\n\t *\n\t * // First call computes and caches the bounding rect\n\t * const rect1 = cache.get(element, (el) => el.getBoundingClientRect())\n\t *\n\t * // Second call returns cached value\n\t * const rect2 = cache.get(element, (el) => el.getBoundingClientRect())\n\t * // rect1 and rect2 are the same object\n\t * ```\n\t */\n\tget<P extends K>(item: P, cb: (item: P) => V) {\n\t\tif (!this.items.has(item)) {\n\t\t\tthis.items.set(item, cb(item))\n\t\t}\n\n\t\treturn this.items.get(item)!\n\t}\n}\n"], "mappings": "AAuBO,MAAM,UAA+B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAM3C,QAAQ,oBAAI,QAAc;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EA2B1B,IAAiB,MAAS,IAAoB;AAC7C,QAAI,CAAC,KAAK,MAAM,IAAI,IAAI,GAAG;AAC1B,WAAK,MAAM,IAAI,MAAM,GAAG,IAAI,CAAC;AAAA,IAC9B;AAEA,WAAO,KAAK,MAAM,IAAI,IAAI;AAAA,EAC3B;AACD;", "names": [] }