mirror of
https://github.com/fankes/beszel.git
synced 2025-10-19 01:39:34 +08:00
refactor: improve runOnce
with weakmap cache
This commit is contained in:
@@ -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
|
||||||
}
|
}
|
||||||
|
Reference in New Issue
Block a user