javascript / expert
Snippet
Encapsulating WeakMap Private Metadata Registries within Svelte Component Context Contracts
Combines Svelte context API with JavaScript Symbols and WeakMaps to attach truly garbage-collectable, hidden metadata objects to component hierarchies without leaking references across boundaries.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import { setContext, getContext } from 'svelte';const PRIVATE_REGISTRY_KEY = Symbol('PrivateRegistryKey');const metadataRegistry = new WeakMap();export function initPrivateContext(ownerToken, initialData) {metadataRegistry.set(ownerToken, initialData);setContext(PRIVATE_REGISTRY_KEY, ownerToken);}export function usePrivateContext(key) {const ownerToken = getContext(PRIVATE_REGISTRY_KEY);if (!ownerToken) return undefined;const metadata = metadataRegistry.get(ownerToken);return metadata ? metadata[key] : undefined;}
svelte
Breakdown
1
const PRIVATE_REGISTRY_KEY = Symbol('PrivateRegistryKey');
Creates a unique non-string symbol key for Svelte context lookup isolation.
2
const metadataRegistry = new WeakMap();
Instantiates a WeakMap holding private metadata keyed by object references for auto garbage collection.
3
metadataRegistry.set(ownerToken, initialData);
Maps private state strictly to the life of the owner token reference.
4
const metadata = metadataRegistry.get(ownerToken);
Retrieves hidden metadata from module-scoped WeakMap using context token.