Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

797 B
Raw Blame
/* Copyright 2026 Marimo. All rights reserved. */
/* oxlint-disable typescript/no-explicit-any */

/**
 * Debounces multiple calls to a loader function, returning the same promise for
 * all calls with the same key.
 */
export function batch<T, REQ extends unknown[]>(
  loader: (...args: REQ) => Promise<T>,
  toKey: (...args: REQ) => string,
) {
  const requestCache = new Map<string, Promise<T>>();

  return (...args: REQ): Promise<T> => {
    const key = toKey(...args);
    if (requestCache.has(key)) {
      // oxlint-disable-next-line typescript/no-non-null-assertion
      return requestCache.get(key)!;
    }

    const requestPromise = loader(...args).finally(() => {
      requestCache.delete(key);
    });

    requestCache.set(key, requestPromise);
    return requestPromise;
  };
}