Write a decorator (Python) / higher-order function (JS) called timer that wraps another function. When the wrapped function runs, the timer should print how long it took, then return the original function's return value unchanged.
The point of this exercise is to practice decorating a function — adding behavior around a function without modifying its code.
Use the @timer decorator syntax:
@timer
def slow_add(a, b):
time.sleep(0.5)
return a + b
slow_add(2, 3)
# prints something like: "slow_add took 0.5021 seconds"
# returns: 5JS does not have stable decorator syntax, so wrap the function manually:
const timedSlowAdd = timer(function slowAdd(a, b) {
// (pretend this is slow)
return a + b;
});
timedSlowAdd(2, 3);
// prints something like: "slowAdd took 0.0001 seconds"
// returns: 5- The print/console message must include the function name and the elapsed time.
- The wrapped function must return the same value as the original.
- It should work with any number of arguments.
- Python:
python timer_tests.py - JS:
node timerTests.js
Extend timer so it accepts a label argument — @timer("expensive call") (Python) or timer(fn, "expensive call") (JS) — and uses that label in the print output instead of the function name.
Stuck? Have a code error? Use the "4 Before Me" debugging checklist to help you solve it!