javascript / expert
Snippet
Pattern Matching Router Built with WeakMap Metadata Storage
Metaprogramming patterns can leverage WeakMap to associate private metadata and execution behavior with object instances without risking memory leaks or polluting object keys. This pattern encapsulates evaluation logic within unexposed map memory while exposing clean polymorphic match interfaces to caller systems.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
const patternRegistry = new WeakMap();class RoutePattern {constructor(matcherFn) {patternRegistry.set(this, matcherFn);}match(candidate) {const fn = patternRegistry.get(this);return fn ? fn(candidate) : false;}}const isUserEvent = new RoutePattern(val => typeof val === 'object' && val?.type === 'USER_ACTION');const isSystemLog = new RoutePattern(val => typeof val === 'string' && val.startsWith('SYS_'));function dispatch(event) {if (isUserEvent.match(event)) return 'Handling user action';if (isSystemLog.match(event)) return 'Handling system log';return 'Unhandled event format';}console.log(dispatch({ type: 'USER_ACTION', id: 42 }));
nodejs
Breakdown
1
const patternRegistry = new WeakMap();
Allocates a weakly referenced map keying class instances to private closure logic.
2
patternRegistry.set(this, matcherFn);
Stores non-enumerable predicate logic linked strictly to instance identity.
3
return fn ? fn(candidate) : false;
Retrieves and executes isolated matcher closures without modifying external object signatures.