createLocalStorageCache.js


SUBMITTED BY: okpalan86

DATE: June 29, 2023, 4:32 p.m.

UPDATED: June 29, 2023, 4:32 p.m.

FORMAT: Text only

SIZE: 1.5 kB

HITS: 324

  1. export const createLocalStorageCache = () => {
  2. const cache = new WeakMap();
  3. const updateLocalStorage = () => {
  4. const cacheData = JSON.stringify(Array.from(cache.entries()));
  5. localStorage.setItem('cache', cacheData);
  6. };
  7. const initializeCacheFromLocalStorage = () => {
  8. const cacheData = localStorage.getItem('cache');
  9. if (cacheData) {
  10. const entries = JSON.parse(cacheData);
  11. entries.forEach(([key, value]) => {
  12. cache.set(key, value);
  13. });
  14. }
  15. };
  16. const setCache = (key, value) => {
  17. cache.set(key, value);
  18. updateLocalStorage();
  19. };
  20. const getCache = (key) => cache.get(key);
  21. const removeCache = (key) => {
  22. cache.delete(key);
  23. updateLocalStorage();
  24. };
  25. const clearCache = () => {
  26. cache.clear();
  27. updateLocalStorage();
  28. };
  29. const setCacheWithExpiry = (key, value, ttl) => {
  30. const now = new Date();
  31. const item = {
  32. value,
  33. expiry: now.getTime() + ttl,
  34. };
  35. setCache(key, item);
  36. };
  37. const getCacheWithExpiry = (key) => {
  38. const item = getCache(key);
  39. if (!item) {
  40. return null;
  41. }
  42. const now = new Date();
  43. if (now.getTime() > item.expiry) {
  44. removeCache(key);
  45. return null;
  46. }
  47. return item.value;
  48. };
  49. initializeCacheFromLocalStorage();
  50. return {
  51. setCache,
  52. getCache,
  53. removeCache,
  54. clearCache,
  55. setCacheWithExpiry,
  56. getCacheWithExpiry,
  57. };
  58. };

comments powered by Disqus