javascriptmonkeypatchingplaycanvas

How to monkey patch a recursive function


I'm using a library () that exposes a function clone() that is called recursively for all the nodes in a hierarchy.

If I monkey patch the function to execute some additional code, this will be executed multiple times.

Instead, I need to execute my code at the end of the whole recursive calls, but I can't find a way to do it.

pc.Entity.prototype.clone = function() {
    ... some code
    // then for each child it calls itself
}

If I try this way I get "my stuff" executed multiple times.

pc.Entity.prototype.cloneOriginal = pc.Entity.prototype.clone;

pc.Entity.prototype.clone = function() {
    var c = this.cloneOriginal();
    // do my stuff
    return c;
}

I need to "override" the clone method so that after all its recursive calls, I can execute my code.


Solution

  • You can achieve that by temporarily restoring the original function before launching it. And when it is finished, you set your trap again, and perform your post processing:

    const orig_clone = pc.Entity.prototype.clone; // Save original clone
    // Set trap:
    pc.Entity.prototype.clone = function patched_clone(...args) {
        pc.Entity.prototype.clone = orig_clone; // Restore original function
        let result = this.clone(...args); // Execute it
        // All is done, including recursion. 
        pc.Entity.prototype.clone = patched_clone; // Set trap again
        // Your code comes here
        console.log('post processing');
        return result;
    }