Measure Function Duration (Profiling Wrapper)
Arguments
fn: () => any | Promise<any> —Function to execute and measure. now: () => number —Optional clock (defaults to performance.now or Date.now).
Returns
Promise<{ result: any, durationMs: number }> — Solution idea
Capture a start time, execute the function, then capture an end time after it finishes. Wrap the result in Promise.resolve so both sync and async paths are handled consistently.
await measure(() => doWork())
await measure(async () => await fetchData(), () => 0)Solution
Overview
Capture a start time, execute the function, then capture an end time after it finishes. Wrap the result in Promise.resolve so both sync and async paths are handled consistently.
Approach: Promise.resolve wrapper
Steps:
1) Record start time.
2) Call fn and wrap with Promise.resolve.
3) After it resolves, record end time and return { result, durationMs }.
4) If fn throws or rejects, propagate the error.
Complexity: O(1) extra work (not counting fn).
export default async function measure(fn, now = () => Date.now()) {
const start = now();
const result = await Promise.resolve().then(fn);
const end = now();
return { result, durationMs: end - start };
}
export default async function measure(
fn: () => any | Promise<any>,
now: () => number = () => Date.now()
): Promise<{ result: any; durationMs: number }> {
const start = now();
const result = await Promise.resolve().then(fn);
const end = now();
return { result, durationMs: end - start };
}
Notes & Pitfalls
Using Date.now() for small durations can be too coarse; prefer performance.now when available. Measuring async work without awaiting gives misleading durations. Profiling adds overhead; keep wrappers lightweight.
Function throws: error should propagate (no swallowing). Async function resolves: duration should cover await time. Clock function can be injected for deterministic tests.
Promise.resolve to normalize sync vs async.
Common mistakes on this challenge
measure wrapper is not timing/promisifying function execution correctly
Wrapper should support sync/async functions uniformly and rethrow errors. Capture start/end timestamps around await Promise.resolve().then(fn).Return { result, durationMs }for successful execution.Allow sync throws and async rejections to propagate without swallowing.
Resources
Similar questions
Guides
Preparing for interviews? Use Frontend Coding Challenges first, then move into a concrete Study Plan before targeted Company Prep.
Built in public
The code behind FrontendAtlas lives on GitHub. A star helps other frontend engineers find it.