想象一个简单的递归函数,我们试图包装它以检测输入和输出。
// A simple recursive function.
const count = n => n && 1 + count(n-1);
// Wrap a function in a proxy to instrument input and output.
function instrument(fn) {
return new Proxy(fn, {
apply(target, thisArg, argumentsList) {
console.log("inputs", ...argumentsList);
const result = target(...argumentsList);
console.log("output", result);
return result;
}
});
}
// Call the instrumented function.
instrument(count)(2);
但是,这仅记录最顶层的输入和输出。我想找到一种方法来拥有count
递归时调用检测版本。
该函数调用count
,这就是您需要包装的内容。你可以做任何一个
const count = instrument(n => n && 1 + count(n-1));
or
let count = n => n && 1 + count(n-1);
count = instrument(count);
对于其他一切,您需要将递归调用的函数动态注入到检测函数中,类似于 Y 组合器的做法。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)