cache-apply.js 974 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. /**
  2. * @param {string} [namespace]
  3. */
  4. const createCache = (namespace, printStats = false) => {
  5. const cache = new Map();
  6. let hit = 0;
  7. if (namespace && printStats) {
  8. process.on('exit', () => {
  9. console.log(`🔋 [cache] ${namespace} hit: ${hit}, size: ${cache.size}`);
  10. });
  11. }
  12. return {
  13. /**
  14. * @template T
  15. * @param {string} key
  16. * @param {() => T} fn
  17. * @returns {T}
  18. */
  19. sync(key, fn) {
  20. if (cache.has(key)) {
  21. hit++;
  22. return cache.get(key);
  23. }
  24. const value = fn();
  25. cache.set(key, value);
  26. return value;
  27. },
  28. /**
  29. * @template T
  30. * @param {string} key
  31. * @param {() => Promise<T>} fn
  32. * @returns {Promise<T>}
  33. */
  34. async async(key, fn) {
  35. if (cache.has(key)) {
  36. hit++;
  37. return cache.get(key);
  38. }
  39. const value = await fn();
  40. cache.set(key, value);
  41. return value;
  42. }
  43. };
  44. };
  45. module.exports.createCache = createCache;