MCPcopy Create free account
hub / github.com/ethanniser/the-beth-stack / cache

Function cache

packages/beth-stack/src/cache/render.ts:4–35  ·  view source on GitHub ↗
(fn: T)

Source from the content-addressed store, hash-verified

2import { BETH_GLOBAL_RENDER_CACHE } from "../shared/global";
3
4export 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
37type CachedValue<T> =
38 | { type: "result"; value: T }

Callers 2

persistedCacheFunction · 0.90

Calls 3

logMethod · 0.80
getMethod · 0.45
setMethod · 0.45

Tested by

no test coverage detected