WeakMap Memoizes By Object Identity
A WeakMap typed as WeakMap<RequestOptions, NormalizedOptions> memoizes per object identity, and only objects can ever become keys.
Code
// WeakMap<K extends object, V> memoizes per object identity, and only
// objects can ever become keys.
interface RequestOptions {
readonly url: string;
readonly retries: number;
}
interface NormalizedOptions {
url: string;
retries: number;
timeoutMs: number;
}
const normalized = new WeakMap<RequestOptions, NormalizedOptions>();
function normalize(options: RequestOptions): NormalizedOptions {
const cached = normalized.get(options);
if (cached) return cached;
const value: NormalizedOptions = {
url: options.url,
retries: options.retries,
timeoutMs: options.retries * 5000 + 2000,
};
normalized.set(options, value);
return value;
}
const fast: RequestOptions = { url: '/api/items', retries: 0 };
const flaky: RequestOptions = { url: '/api/upload', retries: 3 };
console.log('fast:', JSON.stringify(normalize(fast)));
console.log('flaky:', JSON.stringify(normalize(flaky)));
// The second call for the same object returns the identical instance
console.log('memo hit is identical:', normalize(fast) === normalize(fast));
console.log('distinct keys stay distinct:', normalize(fast) === normalize(flaky));Output
Captured from a sandboxed run of this snippet in the build pipeline.
fast: {"url":"/api/items","retries":0,"timeoutMs":2000}
flaky: {"url":"/api/upload","retries":3,"timeoutMs":17000}
memo hit is identical: true
distinct keys stay distinct: falseWhat the code does
WeakMap Memoizes By Object Identity reduces to the function normalize.
What to watch for
- The toolchain by itself is enough — no dependency resolution runs.
- The guard
cachedcuts the flow short right there using an earlyreturnwhen its condition holds.
Applying it
Signature: function normalize(options: RequestOptions)
The output comes back labeled — fast:, flaky:, memo hit is identical: — when the file runs.
Statements that matter
if (cached) return cached;
Interactive Tools for This Topic
FAQ
- Does the runtime need any help from npm, pip, cargo, or the like?
- No — the package manager has nothing to do here; nothing is declared. The file defines `normalize` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.