想象一个简单的递归函数,我们试图将其换行以便输入和输出。
// 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
在递归时调用已检测版本的方法。
答案 0 :(得分:-1)
该函数调用count
,这就是你需要包装的内容。你可以做任何一件事
const count = instrument(n => n && 1 + count(n-1));
或
let count = n => n && 1 + count(n-1);
count = instrument(count);
对于其他所有内容,您需要动态地将递归调用的函数注入到检测函数中,类似于Y组合器的执行方式。