為了了解 using WeakMap,我想出了以下示例來跟蹤函式呼叫:
var map = new WeakMap();
function countFunctionInvocations(func) {
return function(...args) {
map.set(func, (map.get(func) || 0) 1);
return func.apply(this, args);
}
};
const _add = (x,y) => x y;
const _inc = x => x 1;
const add = countFunctionInvocations(_add);
const inc = countFunctionInvocations(_inc);
add(2,3);
add(1,2);
add(2,3);
add(2,3);
inc(inc(1));
console.log(map.get(_add), map.get(_inc));
// 4 2
什么是實作這一點的更簡潔的方法,因為我必須來回給函式起別名,例如 from addto_add和 back to add。另外,以上是 Weakmap 的合法使用嗎?
uj5u.com熱心網友回復:
WeakMap 的使用非常奇怪 - 正如您所注意到的,如果您想用函式查找它,您必須將這些函式存盤在變數中,這些變數與 count-invokified 函式分開。只要您沒有函式名稱沖突,它就會使事情變得尷尬,并且 WeakMap 似乎沒有比普通物件帶來凈收益。
如果您要查找的內容允許這樣做,則可以傳遞另一個引數來countFunctionInvocations指示名稱,從而允許您傳遞(簡潔,匿名)箭頭函式。
const counts = {};
function countFunctionInvocations(name, func) {
return function(...args) {
counts[name] = (counts[name] ?? 0) 1;
console.log("called", name, counts[name]);
return func.apply(this, args);
}
};
const add = countFunctionInvocations('add', (x,y) => x y);
const inc = countFunctionInvocations('inc', x => x 1);
add(2,3);
add(1,2);
add(2,3);
add(2,3);
inc(inc(1));
console.log(counts.add, counts.inc);
另外,以上是 Weakmap 的合法使用嗎?
我的意思是,它可以被使用,但正如我們已經注意到的那樣 - 必須有兩個單獨的函式參考是很尷尬的 - 一個是基本函式,一個是由countFunctionInvocations.
也就是說,這肯定是 WeakMap在 Map 上的合法使用,因為它允許函式(及其呼叫計數)在沒有其他東西可以參考它時被垃圾收集。
我想另一種選擇是將回傳的函式作為放入 Map 的函式,這樣您在外部只有一個識別符號,但它需要一個function或第二個引數來指示函式的名稱,否則inside ofcountFunctionInvocations只會看到一個沒有名字的匿名函式。
const map = new WeakMap();
function countFunctionInvocations(func) {
const fn = (...args) => {
map.set(fn, (map.get(fn) || 0) 1); // use returned function in Map
return func.apply(this, args); // invoke passed function
}
return fn;
};
const add = countFunctionInvocations(function add(x, y) { return x y });
const inc = countFunctionInvocations(function inc(x) { return x 1 });
add(2,3);
add(1,2);
add(2,3);
add(2,3);
inc(inc(1));
console.log(map.get(add), map.get(inc));
// 4 2
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/476029.html
標籤:javascript 弱图
