Skip to content

Instantly share code, notes, and snippets.

@tannerlinsley
Created June 6, 2025 16:54
Show Gist options
  • Save tannerlinsley/eedfabb773357a0ef0bb9ffa30ccf1ba to your computer and use it in GitHub Desktop.
Save tannerlinsley/eedfabb773357a0ef0bb9ffa30ccf1ba to your computer and use it in GitHub Desktop.

Revisions

  1. tannerlinsley created this gist Jun 6, 2025.
    9 changes: 9 additions & 0 deletions README.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,9 @@
    `createCachedFn` function wraps any function fn in a cache that is scoped to the current “event” (via getEvent()), ensuring repeat calls with the same arguments during that event return cached results instead of recomputing.

    Summary:
    • Caches function results per event.
    • Uses fn.toString() and JSON.stringify(args) as cache keys.
    • Stores cache in a per-event __cachedStorage map.
    • Avoids recomputation for repeated calls with the same arguments during the same event.

    It’s ideal for optimizing repeated pure function calls during a single request or lifecycle event.
    42 changes: 42 additions & 0 deletions createCachedFn.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,42 @@
    export function createCachedFn<T extends (...args: any[]) => any>(fn: T) {
    return (...args: Parameters<T>): ReturnType<T> => {
    const event = getEvent(); // Retrieve the event dynamically

    // Ensure __cachedStorage exists on the event
    if (!event.__cachedStorage) {
    event.__cachedStorage = new Map<string, any>();
    }

    const cache = event.__cachedStorage;
    const fnKey = fn.toString(); // Unique key for the function
    const argsKey = JSON.stringify(args); // Unique key for the arguments

    // Ensure a cache exists for this specific function
    if (!cache.has(fnKey)) {
    cache.set(fnKey, new Map());
    }

    const fnCache = cache.get(fnKey);

    // Check for cached result
    if (fnCache.has(argsKey)) {
    return fnCache.get(argsKey);
    }

    // Compute result, store in cache
    const result = fn(...args);
    fnCache.set(argsKey, result);

    return result;
    };
    }

    // Example usage
    const myFn = (x: number, y: number) => x + y;

    const cachedFn = createCachedFn(myFn);

    // Calling the cached function
    console.log(cachedFn(5, 3)); // Calls myFn(5, 3) and caches
    console.log(cachedFn(5, 3)); // Returns cached value
    console.log(cachedFn(2, 4)); // Calls myFn(2, 4) - Different params