import { TObject } from "."; import { dlog } from "./dlog"; export namespace dcache { /* https://www.sitepoint.com/implementing-memoization-in-javascript/ function pow(a, b) { return a ** b; } // creates the memoized version pow = memoize(pow); pow(3, 5); // creates the index "[3,5]" and returns 243 */ // make sure you have used await export function memoizeAsync(func: Function, timeoutms?: number, customKey?: string) { const cache: TObject = {}; return async function memoized(...args: any) { const key = customKey || JSON.stringify(args); if (!cache[key]) { cache[key] = await func(...args); if (timeoutms) { setTimeout(() => { cache[key] = undefined; }, timeoutms); } } else { dlog.d("perf:avoid call as cache founds"); } return cache[key]; }; } // just call export function memoize(func: Function, timeoutms?: number, customKey?: string) { const cache: TObject = {}; return function memoized(...args: any) { const key = customKey || JSON.stringify(args); if (!cache[key]) { cache[key] = func(...args); if (timeoutms) { setTimeout(() => { cache[key] = undefined; }, timeoutms); } } else { dlog.d("perf:avoid call as cache founds"); } return cache[key]; }; } export function ensureOneCallAsync(func: Function): (...args: any) => Promise { const cache: TObject = {}; return async function memoized(...args: any) { const key = JSON.stringify(args); if (!cache[key]) { cache[key] = true; try { await func(...args); cache[key] = false; } catch (e) { cache[key] = false; throw e; } } else { dlog.d("perf:avoid call as other ongoing"); } }; } } // test