cache-apply.ts 737 B

12345678910111213141516171819202122232425262728293031
  1. export const createCache = (namespace?: string, printStats = false) => {
  2. const cache = new Map();
  3. let hit = 0;
  4. if (namespace && printStats) {
  5. process.on('exit', () => {
  6. console.log(`🔋 [cache] ${namespace} hit: ${hit}, size: ${cache.size}`);
  7. });
  8. }
  9. return {
  10. sync<T>(key: string, fn: () => T): T {
  11. if (cache.has(key)) {
  12. hit++;
  13. return cache.get(key);
  14. }
  15. const value = fn();
  16. cache.set(key, value);
  17. return value;
  18. },
  19. async async<T>(key: string, fn: () => Promise<T>): Promise<T> {
  20. if (cache.has(key)) {
  21. hit++;
  22. return cache.get(key);
  23. }
  24. const value = await fn();
  25. cache.set(key, value);
  26. return value;
  27. }
  28. };
  29. };