Problem, as an interviewer would state it:
"Write once(fn) — it returns a new function that, no matter how many times it's called, only ever actually invokes fn the first time. Every subsequent call should return whatever the first call returned, without running fn again."
Examples:
const init = once(() => { console.log("running"); return 42; });
init(); // logs "running", returns 42
init(); // does NOT log, returns 42 again
Clarifying questions expected:
- Should later calls' arguments be used for anything, or always ignored once the function has run?
- Does
thisneed to be preserved iffnrelies on it? - Should the cached result be memory-cleared eventually, or live forever with the closure?
Code / implementation expected: Yes — real, direct proof the underlying function's call count stays at 1 even after multiple invocations, and that the returned value is genuinely cached, not recomputed.