WeakMap.prototype.getOrInsertComputed()
getOrInsertComputed()
方法是 WeakMap
实例上的一个方法,用于返回此 WeakMap
中与指定键关联的值。如果键不存在,它将使用给定的回调函数计算出一个默认值,并将键和该默认值一起插入到 WeakMap 中,然后返回这个插入的值。
当默认值计算成本高昂,并且您希望避免不必要的计算时,请使用此方法而不是 WeakMap.prototype.getOrInsert()
。
试一试
const alan = { name: "Alan" };
const map = new WeakMap([[alan, 35]]);
const defaultCreator = (obj) => `${obj.name}'s age is unknown`;
console.log(map.getOrInsertComputed(alan, defaultCreator));
// Expected output: 35
const brett = { name: "Brett" };
console.log(map.getOrInsertComputed(brett, defaultCreator));
// Expected output: "Brett's age is unknown"
语法
js
getOrInsertComputed(key, callback)
参数
key
-
要从
Map
对象返回的元素的键。必须是对象或 未注册的 symbol。对象键通过 引用 进行比较,而不是通过值。 回调
-
一个函数,用于在键尚未存在于
Map
对象中时返回要插入并返回的值。该函数将使用以下参数调用:key
-
传递给
getOrInsertComputed()
的同一个键。
返回值
与 WeakMap
对象中指定键关联的值。如果找不到键,则插入并返回 callback(key)
的结果。
示例
缓存
缓存涉及从一个昂贵函数的参数到其返回值的映射,以便将来使用相同参数调用时可以返回缓存的值而不是重新计算。当不存在缓存值时,需要将其计算并插入到缓存中。
我们在这里使用 WeakMap
而不是 Map
,以便当缓存的参数值不再需要在程序其他地方使用时,它们不会阻止其被垃圾回收。如果您的缓存函数接受非对象参数,则可以使用 Map
。
js
// Any expensive function you want to cache
function computeExpensiveValue(requestOptions) {
// Imagine expensive computation, like fetching data or complex calculations
console.log(`Fetching from ${requestOptions.url}`);
return new Response("Fake response");
}
// A higher-order function that adds caching to any function
function withCache(fn) {
const cache = new WeakMap();
return (param) => cache.getOrInsertComputed(param, fn);
}
const computeWithCache = withCache(computeExpensiveValue);
const options = { url: "https://example.com/a", method: "GET" };
const value1 = computeWithCache(options); // Logs "Fetching from https://example.com/a"
const value2 = computeWithCache(options); // No log
规范
规范 |
---|
Upsert (更新或插入) # sec-weakmap.prototype.getOrInsertComputed |
浏览器兼容性
加载中…