Problem: Measure Execution Time for an Async Task
Problem statement
You’re simulating a service call that takes some time to complete, maybe fetching data from a database or an external API. You need to measure how long this operation takes, but you can’t alter the service function directly. You’ll use a decorator to wrap it, measure its duration, and log the timing details.
Goal
Create a withTiming decorator that:
Measures how long the wrapped async function takes to resolve.
Logs the duration in milliseconds.
Returns the original function’s result.
Constraints
Do not modify the original async function.
The decorator should log the time after the function completes.
Do not use any external libraries for timing.
Sample output
The examples below illustrate what the output should look like:
const timedFetch = withTiming(fetchUser);(async () => {await timedFetch(42); // should log how long it tookawait timedFetch(7); // should log again})();/* Expected output (might vary):[TIMER] fetchUser took 103ms[TIMER] fetchUser took 99ms */
Good luck trying the problem! If you’re unsure how to proceed, check the “Solution” tab above.
Problem: Measure Execution Time for an Async Task
Problem statement
You’re simulating a service call that takes some time to complete, maybe fetching data from a database or an external API. You need to measure how long this operation takes, but you can’t alter the service function directly. You’ll use a decorator to wrap it, measure its duration, and log the timing details.
Goal
Create a withTiming decorator that:
Measures how long the wrapped async function takes to resolve.
Logs the duration in milliseconds.
Returns the original function’s result.
Constraints
Do not modify the original async function.
The decorator should log the time after the function completes.
Do not use any external libraries for timing.
Sample output
The examples below illustrate what the output should look like:
const timedFetch = withTiming(fetchUser);(async () => {await timedFetch(42); // should log how long it tookawait timedFetch(7); // should log again})();/* Expected output (might vary):[TIMER] fetchUser took 103ms[TIMER] fetchUser took 99ms */
Good luck trying the problem! If you’re unsure how to proceed, check the “Solution” tab above.