refactor: improve runOnce with weakmap cache

This commit is contained in:
henrygd
2025-09-01 18:34:29 -04:00
parent 9c458885f1
commit 890bad1c39

View File

@@ -348,15 +348,20 @@ export function debounce<T extends (...args: any[]) => any>(func: T, wait: numbe
} }
} }
// Cache for runOnce
const runOnceCache = new WeakMap<Function, { done: boolean; result: unknown }>()
/** Run a function only once */ /** Run a function only once */
export function runOnce<T extends (...args: any[]) => any>(fn: T): (...args: Parameters<T>) => ReturnType<T> { export function runOnce<T extends (...args: any[]) => any>(fn: T): T {
let done = false return ((...args: Parameters<T>) => {
let result: any let state = runOnceCache.get(fn)
return (...args: any) => { if (!state) {
if (!done) { state = { done: false, result: undefined }
result = fn(...args) runOnceCache.set(fn, state)
done = true
} }
return result if (!state.done) {
} state.result = fn(...args)
state.done = true
}
return state.result
}) as T
} }