Skip to content

CodeNot attempted

once()

Difficulty: easy

Return a function that calls fn only the first time. Every later call returns the first result.

  • keep this and the arguments of the first call
  • an undefined result still counts as "called"

Real use: init code, one-time event handlers.

Show reference solution
export function once<A extends unknown[], R>(fn: (...args: A) => R): (...args: A) => R {
let hasRun = false; // a flag, so a result of undefined is remembered too
let result: R;
return function (this: unknown, ...args: A) {
if (!hasRun) {
hasRun = true;
result = fn.apply(this, args);
}
return result;
};
}
Loading editor…