Usecase: I want to get how much time a function takes to execute in typescript. I want to use decorator for this purpose.
I want the decorator should return the time so that (I can further use it), not just print it.
For eg :
export function createTimestamps(message: string) {
return function (target: any, name: string, descriptor: PropertyDescriptor) {
const method = descriptor.value;
descriptor.value = async function () {
const startTime = new Date(Date.now());
console.log(
`${message} started at: ${startTime.toLocaleString("en-GB")}`
);
await method.apply(this);
const endTime = new Date(Date.now());
console.log(
`${message} completed at: ${endTime.toLocaleString("en-GB")}`
);
console.log(
`${message} took ${
endTime.getTime() - startTime.getTime()
}ms to complete.`
);
};
};
}
If I use above function as decorator , then I would like the decorator to return "endTime.getTime() - startTime.getTime()" , so that I can further use it .
@creaTimestamp
async newfunc():string{
return "typescript";
}
Now when I call above function await newfunc(). Can I get execution time value as well along with the string it is returning ?
Also I have many functions I want to avoid adding decorator on top of each one of them, and thus while calling them I want make sure that the decorator runs and returns the timing as well. Can someone point me to such library if exist ?
Can someone please share some insight in above scenarios, I am very new to decorators. Thanks!