(fn: T)
| 2 | import { BETH_GLOBAL_RENDER_CACHE } from "../shared/global"; |
| 3 | |
| 4 | export function cache<T extends (...args: any[]) => any>(fn: T): T { |
| 5 | return ((...args: unknown[]) => { |
| 6 | const cachedResults = BETH_GLOBAL_RENDER_CACHE.dedupeCache.get(fn); |
| 7 | |
| 8 | if (cachedResults) { |
| 9 | for (let [keyArgs, cachedValue] of cachedResults.entries()) { |
| 10 | if (Bun.deepEquals(args, keyArgs, true)) { |
| 11 | if (cachedValue.type === "error") { |
| 12 | console.log("throwing cached error"); |
| 13 | throw cachedValue.error; |
| 14 | } else { |
| 15 | console.log("returning cached value"); |
| 16 | return cachedValue.value; |
| 17 | } |
| 18 | } |
| 19 | } |
| 20 | } else { |
| 21 | const newCache = new Map(); |
| 22 | |
| 23 | BETH_GLOBAL_RENDER_CACHE.dedupeCache.set(fn, newCache); |
| 24 | |
| 25 | try { |
| 26 | const functionResult = fn(...args); |
| 27 | newCache.set(args, { type: "result", value: functionResult }); |
| 28 | return functionResult; |
| 29 | } catch (error) { |
| 30 | newCache.set(args, { type: "error", error }); |
| 31 | throw error; |
| 32 | } |
| 33 | } |
| 34 | }) as T; |
| 35 | } |
| 36 | |
| 37 | type CachedValue<T> = |
| 38 | | { type: "result"; value: T } |
no test coverage detected