I want to create a simple performance logger:
function makePerformanceMeasured(target) {
return new Proxy(target, {
apply: (target, thisArg, args) => {
if(!target.name) {
throw 'The function must have a name'
}
console.time(target.name);
const result = target.apply(thisArg, args);
console.timeEnd(target.name);
return result;
}
})
}
for non-recursive functions - everything works well:
function isPrime(n) {
if(n < 2) {
return false;
}
for(var i = 0; i < n; i++) {
if(n % i === 0) {
return false;
}
}
return true;
}
isPrime = makePerformanceMeasured(isPrime);
isPrime(100);
But with recursive functions:
function fact(n) {
if(n < 2) {
return 1;
}
return n * fact(n - 1);
}
fact = makePerformanceMeasured(fact);
fact(4);
I want to detect in the trap Proxy apply
- if the function was called recursively - take time measurements only for the first function call on the stack. Thank!
source
share