function once(fn) {
let called = false, result;
return function(...args) {
if (!called) { called = true; result = fn.apply(this, args); }
return result;
};
}The once decorator ensures a function executes only on the first call.
A decorator can ensure a function only runs once, then returns the cached result.
Challenge: Implement an once(fn) decorator that wraps a function. The first call executes fn, but subsequent calls return the cached result without executing fn again.
Example:
let callCount = 0
const fn = (x) => { callCount++; return x * 2 }
const o = once(fn)
o(5) // calls fn, returns 10, callCount = 1
o(99) // returns cached 10, callCount still 1