Proxy recursive function

Imagine a simple recursive function that we are trying to wrap for input and output of a tool.

// 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);
Run codeHide result

However, this only registers entry and exit at the highest level. I want to find a way to countinvoke the instrumental version when it repeats.

+4
source share
1 answer

The function calls count, so this 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 will need to dynamically insert a function for a recursive call into a tool function, similar to how Y combinator does it.

-1
source

Source: https://habr.com/ru/post/1665823/


All Articles