Skip to curriculum
Jump to the editor

6.8. Log every call's time without changing the function

Medium
Topics

This question is in

6. Functions and closures
20–30 min

A page feels slow, and you suspect one function: the one that filters a long list, or the one that loads prices from the server. You want to know when each call happened and how long it took, without editing the function, because it comes from a library or is used in fifty places. The answer is a wrapper: a function that looks and behaves like the original, and reports on every call.

Write logCalls(fn, log) in log-calls.js. It returns a wrapper that runs fn exactly as a direct call would, and calls log once per call with a report of that call.

Signature

JAVASCRIPT
function logCalls(fn, log) // returns a function
  • fn: the function to measure.
  • log: a function that receives one entry per call: { name, args, startedAt, duration, ok }.
    • name: fn.name, or "anonymous" when it is empty.
    • args: the call's arguments, as an array.
    • startedAt: Date.now() at the moment the call began.
    • duration: milliseconds from the start of the call to its end, measured with performance.now().
    • ok: true when the call finished normally, false when fn threw or its promise rejected.
  • The wrapper returns whatever fn returns, and has the same name and length as fn.

Requirements

  1. logCalls returns a function and calls neither fn nor log itself.
  2. The wrapper passes its this and every argument to fn and returns fn's result unchanged, falsy results included. It calls fn itself, even when fn has its own property named apply or call.
  3. After each call, log is called exactly once, after fn has run, with an entry that has exactly the five fields above.
  4. startedAt is the time the call began, and duration is the time spent in the call.
  5. If fn throws, the same error is thrown to the caller, after log has received an entry with ok: false.
  6. If fn returns a promise (any object with a then method), the wrapper returns that same promise, and log is called when it settles: ok: true when it fulfills, false when it rejects, with the duration up to that moment. Settling means the final outcome, the one await would give: a thenable that resolves with another promise or thenable is logged when that one settles, with that one's outcome. The caller still sees the rejection, and the wrapper adds no unhandled rejection of its own. A call is logged once even when a thenable calls back more than once: the first outcome counts, as it would for a real promise. If the thenable's then throws, the wrapper still returns the thenable: a throw after it has called back changes nothing, and a throw before it calls back is logged as ok: false, as await treats it.
  7. Each call is logged on its own, a call nested inside another included (the inner call is logged first).
  8. fn is not changed in any way, and the wrapper has fn's name and length.

Examples

JAVASCRIPT
const entries = [];
const slowSquare = (n) => { /* …takes 30 ms… */ return n * n; };
const square = logCalls(slowSquare, (entry) => entries.push(entry));

square(4); // 16
entries;   // [{ name: "slowSquare", args: [4], startedAt: 1700000000000, duration: 30, ok: true }]
JAVASCRIPT
const load = logCalls(async function loadPrices(id) { /* fetch… */ }, console.log);
load(7);   // returns the promise; nothing is logged yet
// when the promise settles (say 120 ms later):
// { name: "loadPrices", args: [7], startedAt: …, duration: 120, ok: true }
JAVASCRIPT
const parse = logCalls(JSON.parse, console.log);
parse("{");  // throws SyntaxError, after logging { name: "parse", args: ["{"], …, ok: false }
parse.name;  // "parse"

Environment

  • Plain JavaScript in a browser page; the tests call the global logCalls from log-calls.js.
  • The tests run on a virtual clock that replaces Date.now, performance.now and the timers, and the functions they measure move that clock forward. So read the time with Date.now() and performance.now(), at the moment the call starts and ends.
  • fn and log are always functions. A log that throws is out of scope.

Hints

  1. Where do you need the start time: in the wrapper's closure, shared by every call, or in each call?
  2. A try/catch can log a failure, but how do you make sure the caller still gets the error?
  3. For a promise, which method lets you run code on both fulfillment and rejection without handling the rejection for the caller?

The explanation comes with the course

A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.

  • Every line explained
  • The mistakes each test catches
  • Links to the lessons behind it
Back to the question
Loading the editor…