function once(fn) {
let called = false, result
return (...args) => {
if (!called) { called = true; result = fn(...args) }
return result
}
}
const init = once(() => 'initialized')
init() // β 'initialized'
init() // β 'initialized' (fn not called again)Closures preserve flags and cached results across calls, making it easy to execute a function only once and reuse its result.
Create a wrapper that ensures a function is called at most once, ignoring subsequent calls.
Challenge: Create a once(fn) function that returns a wrapper. The first time the wrapper is called, it executes fn and caches the result. All subsequent calls return the cached result without executing fn again.
Example:
let n = 0
const increment = () => ++n
const onceIncrement = once(increment)
onceIncrement() // 1, n becomes 1
onceIncrement() // 1, n stays 1
onceIncrement() // 1, n stays 1