cache-apply.ts 774 B

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