Proxying a recursive function

徘徊边缘 提交于 2019-12-10 17:12:08

问题


Imagine a simple recursive function, which we are trying to wrap in order to instrument input and output.

// 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);

However, this only logs the input and output at the topmost level. I want to find a way to have count invoke the instrumented version when it recurses.


回答1:


The function invokes count, so that is what you need to wrap. You can do either

const count = instrument(n => n && 1 + count(n-1));

or

let count = n => n && 1 + count(n-1);
count = instrument(count);

For everything else, you would need to dynamically inject the function for the recursive call into the instrumented function, similar to how the Y combinator does it.



来源:https://stackoverflow.com/questions/41478219/proxying-a-recursive-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!