Exercise 19: Function Logger (call logging)

Problem Statement

Create a function `withLogger(fn, label)` that logs function calls.

Sample Output:

const logged = withLogger((x) => x * 2, "Double");
logged(5) => 10
// Console: "[Double] Called with: [5]"
// Console: "[Double] Returned: 10"

Solution

const withLogger = (fn, label = "Function") => {
  return (...args) => {
    console.log(`[${label}] Called with:`, args);
    const result = fn(...args);
    console.log(`[${label}] Returned:`, result);
    return result;
  };
};

Explanation

Overall Goal:

  • Function calls ko log karna.

Real world:

  • Debugging: function call tracking.
  • Monitoring: function usage analytics.