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.
logCalls returns a function and calls neither fn nor log itself.
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.
After each call, log is called exactly once, after fn has run, with an entry that has exactly the five fields above.
startedAt is the time the call began, and duration is the time spent in the call.
If fn throws, the same error is thrown to the caller, after log has received an entry with ok: false.
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.
Each call is logged on its own, a call nested inside another included (the inner call is logged first).
fn is not changed in any way, and the wrapper has fn's name and length.
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.