Middle
** * Implement a runOnce wrapper function that takes * a function and returns a new function. The new function * can only be called once, all subsequent * calls return undefined. * * The wrapped function can accept arguments * and return a result. */ function runOnce(fn) { // your code } const logHello = (name) => { console.log(`hello, ${name}!`) }; const logHelloOnce = runOnce(logHello); console.clear(); logHelloOnce('Oleg'); // 'hello, Oleg!' logHelloOnce('Olga'); // undefined","locale":"kk"}]},{
sobes.tech AI
Answer from AI
javascript function runOnce(fn) { let called = false; return function(...args) { if (called) return undefined; called = true; return fn.apply(this, args); }; }
const logHello = (name) => {
console.log(hello, ${name}!);
};
const logHelloOnce = runOnce(logHello); console.clear(); logHelloOnce('Oleg'); // 'hello, Oleg!' logHelloOnce('Olga'); // undefined
The `runOnce` function creates a closure with a `called` flag. When the wrapped function is called for the first time, it invokes the original function with the provided arguments and sets the flag. All subsequent calls return `undefined` and do not invoke the original function.