/* 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( loader: (...args: REQ) => Promise, toKey: (...args: REQ) => string, ) { const requestCache = new Map>(); return (...args: REQ): Promise => { 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; }; }