CodeNot attempted
once()
Difficulty: easy
Return a function that calls fn only the first time. Every later call returns the first result.
- keep
thisand the arguments of the first call - an
undefinedresult 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; };}
Ctrl Enter