Exercise 17: Function Timer (execution time)

Problem Statement

Create a function `withTimer(fn)` that wraps function and measures execution time.

Sample Output:

const timed = withTimer((n) => n * 2);
timed(5) => 10
// Console: "Execution time: 0.1ms"

Solution

const withTimer = (fn) => {
  return (...args) => {
    const start = performance.now();
    const result = fn(...args);
    const end = performance.now();
    console.log(`Execution time: ${end - start}ms`);
    return result;
  };
};

Explanation

Overall Goal:

  • Function execution time measure karna.

Real world:

  • Performance profiling: function timing.
  • Debugging: slow operations identify.