Home > OS >  Adding logs within a wrapped function
Adding logs within a wrapped function

Time:05-14

I have created a function wrapper to help give me various print statements:

function fnWrapper(fn, verbosity=false) {
    return function(...rest) {
        if (verbosity) console.log(`Calling "${fn.name}(${rest})"`)
        const res = fn(...rest); // possible to add debugging **within** this wrapped function?
        if (verbosity) console.log('==>', res)
        return res;
    }
}
function add(x,y) {
     return x===0 ? y : add(x-1, y 1);
}
const add2 = fnWrapper(add, true);

add2(2,3);
// Calling "add(2,3)"
// ==> 5

Is it possible to add debugging within the function itself, for example, at its most basic to translate a function such as the following:

function something(x,y) {
    console.log(arguments); // add this in
    ...
}

So for the above function it would make the add become:

function add(x,y) {
    console.log(arguments);
    return x===0 ? y : add(x-1, y 1);
}

If so, how could that be done?

CodePudding user response:

No, this is not possible, you cannot change what a function does.

The problem is that add calls add, and add2 also calls add only. You can however simply replace add:

function fnWrapper(fn, verbosity=false) {
    return function(...rest) {
        if (verbosity) console.log(`Calling "${fn.name}(${rest})"`)
        const res = fn.call(this, ...rest);
        if (verbosity) console.log('==>', res)
        return res;
    }
}
function add(x,y) {
     return x===0 ? y : add(x-1, y 1);
}
add = fnWrapper(add, true); /*
^^^ */

add(2,3);

  • Related