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 |
瀏覽器相容性
載入中…