实现说明
逻辑集中在函数 normalize里。
使用要点
- 守卫
cached满足时靠提前的return短路流程。 - 每一步打印都带着自己的标签:
fast:、flaky:、memo hit is identical:。
常见问题
运行时需要 npm、pip、cargo 之类帮忙吗?
不需要——包管理器在这里无事可做,没有任何声明。 文件在加载时定义 normalize。
主签名形如 function normalize(options: RequestOptions)
核心语句
if (cached) return cached;
代码示例
// 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));