Proxying a recursive function

182 views Asked by At

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

There are 1 answers

0
Bergi On

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.