Browser-safe, symbol-keyed storage utilities.
The cache is a singleton scoped to the loaded module instance and works in current browsers, Node, Deno, and Bun.
import kv from "@rcompat/kv";
import type { Cache } from "@rcompat/kv";kv.cache#
The shared symbol-keyed cache.
kv.cache: Cache;Cache methods#
kv.cache.get()#
Gets a cached value, optionally initializing a missing key.
Keys use symbol identity, not their descriptions. Without an initializer,
a missing key returns undefined. With an initializer, its return value,
including undefined or a promise, is stored before being returned. If the
initializer throws, no value is stored and a later call can try again.
Type parameters
Contents— Type stored under the key.
Parameters
key— Symbol key to look up.init— Synchronous initializer called only for a missing key.
Returns: The cached or initialized value, or undefined when missing.
Example
const key = Symbol("config");
const first = kv.cache.get(key, () => ({ enabled: true }));
kv.cache.get(key) === first; // truekv.cache.get<Contents>(key: symbol): Contents | undefined;
kv.cache.get<Contents>(key: symbol, init: () => Contents): Contents;Supporting contracts#
Cache#
A symbol-keyed cache with optional lazy initialization.
interface Cache {
// Gets a cached value, optionally initializing a missing key.
get<Contents>(key: symbol): Contents | undefined;
get<Contents>(key: symbol, init: () => Contents): Contents;
}