工具函数 · 12/107
1. 抽象工厂模式 2. Adapter Pattern 3. Adapter Pattern 4. 实现一个支持柯里化的 add 函数 5. 计算两个数组的交集 6. 数组中的数据根据key去重 7. 实现一个add方法完成两个大数相加 8. 大数相加 9. bind、call、apply 的区别与实现 10. Bridge Pattern 11. Builder Pattern 12. 实现一个管理本地缓存过期的函数 13. 缓存代理 14. 转化为驼峰命名 15. 实现 (5).add(3).minus(2) 功能 16. 咖啡机进阶优化 17. 咖啡机状态管理 18. 常用设计模式总结 19. 咖啡机状态切换机制 20. 查找数组公共前缀(美团) 21. 实现一个compose函数 22. 并发请求调度器 23. 组合模式 24. 实现 console.log 代理方法 25. Decorator Pattern 26. 实现防抖和节流 27. 实现一个JS函数柯里化 28. 实现防抖函数(debounce) 29. Decorator Pattern 30. 手写深度比较isEqual 31. 消除 if-else 条件判断 32. 修改嵌套层级很深对象的 key 33. 设计模式应用 34. 验证是否是邮箱 35. 实现发布订阅模式 36. 外观模式 37. Facade Pattern 38. Factory Pattern 39. 工厂模式 40. 工厂模式实现 41. Flyweight Pattern 42. 前端常用设计模式与场景 43. 提取对象中所有value大于2的键值对 44. 用正则实现根据name获取cookie中的值 45. 获取今天的日期 46. ES6 之前的迭代器模式 47. 实现 getValue/setValue 函数来获取path对应的值 48. 验证是否是身份证 49. 迭代器模式 50. jQuery slideUp 动画队列堆积问题 51. 实现一个JSON.parse 52. 实现 LazyMan 任务队列 53. 实现一个JSON.stringify 54. 实现lodash的chunk方法--数组按指定长度拆分 55. 字符串最长的不重复子串 56. LRU 缓存算法 57. 查找字符串中出现最多的字符和个数 58. new 操作符的实现原理 59. 中介者模式 60. 中介者模式 61. 对象数组如何去重 62. 千分位格式化 63. 实现观察者模式 64. 观察者模式实例 65. 观察者模式 66. 实现观察者模式 67. 实现 padStart() 和 padEnd() 的 Polyfill 68. 判断是否是电话号码 69. Proxy Pattern 70. 代理模式:婚介所 71. Proxy Pattern 72. 代理模式 73. 实现上拉加载和下拉刷新 74. 生成随机数组并排序 75. 大文件断点续传实现 76. 使用 setInterval 模拟实现 setTimeout 77. 重构询价逻辑 78. 实现一个简单的路由 79. setTimeout 模拟实现 setInterval 80. RGB 转 Hex 颜色转换 81. setTimeout与setInterval实现 82. Simple Factory Pattern 83. 实现单例模式 84. 实现一个 sleep 函数 85. 状态模式 86. State Pattern 87. 策略模式 88. Strategy Pattern 89. Storage 单例封装 90. 策略模式 91. 计算字符串字节长度 92. 字符串压缩算法实现 93. 字符串查找 94. 字符串去除前后空格 95. 实现模板引擎 96. 实现千位分隔符 97. 实现模板字符串解析功能 98. 实现一个函数判断数据类型 99. Promise 实现红绿灯交替 100. 实现节流函数(throttle) 101. 从指定数据源生成长度为 n 的不重复随机数组 102. 解析 URL Params 为对象 103. URL 验证 104. 判断括号字符串是否有效 105. 虚拟代理 106. 访问者模式 107. 版本号排序的方法

实现一个管理本地缓存过期的函数

封装 localStorage,实现带过期时间的本地缓存管理功能

问题

原生的 localStorage 只能永久存储数据,不支持设置过期时间。在实际开发中,我们经常需要为缓存数据设置有效期,过期后自动失效。本题要求实现一个带过期时间管理的本地缓存工具函数。

解答

class CacheStorage {
  constructor(storage = localStorage) {
    this.storage = storage;
  }

  /**
   * 设置缓存
   * @param {string} key - 缓存键名
   * @param {any} value - 缓存值
   * @param {number} expire - 过期时间(毫秒),不传则永久有效
   */
  set(key, value, expire) {
    const data = {
      value,
      expire: expire ? Date.now() + expire : null
    };
    
    try {
      this.storage.setItem(key, JSON.stringify(data));
    } catch (error) {
      console.error('缓存设置失败:', error);
    }
  }

  /**
   * 获取缓存
   * @param {string} key - 缓存键名
   * @returns {any} 缓存值,过期或不存在返回 null
   */
  get(key) {
    try {
      const item = this.storage.getItem(key);
      
      if (!item) {
        return null;
      }

      const data = JSON.parse(item);
      
      // 检查是否过期
      if (data.expire && Date.now() > data.expire) {
        this.remove(key);
        return null;
      }

      return data.value;
    } catch (error) {
      console.error('缓存读取失败:', error);
      return null;
    }
  }

  /**
   * 删除缓存
   * @param {string} key - 缓存键名
   */
  remove(key) {
    this.storage.removeItem(key);
  }

  /**
   * 清空所有缓存
   */
  clear() {
    this.storage.clear();
  }

  /**
   * 检查缓存是否存在且未过期
   * @param {string} key - 缓存键名
   * @returns {boolean}
   */
  has(key) {
    return this.get(key) !== null;
  }

  /**
   * 清理所有过期缓存
   */
  clearExpired() {
    const keys = Object.keys(this.storage);
    
    keys.forEach(key => {
      try {
        const item = this.storage.getItem(key);
        if (item) {
          const data = JSON.parse(item);
          if (data.expire && Date.now() > data.expire) {
            this.remove(key);
          }
        }
      } catch (error) {
        // 忽略解析错误的项
      }
    });
  }
}

// 创建默认实例
const cache = new CacheStorage();

// 导出函数式 API
export const setCache = (key, value, expire) => cache.set(key, value, expire);
export const getCache = (key) => cache.get(key);
export const removeCache = (key) => cache.remove(key);
export const clearCache = () => cache.clear();
export const hasCache = (key) => cache.has(key);
export const clearExpiredCache = () => cache.clearExpired();

export default cache;

使用示例

// 示例 1: 基本使用
cache.set('username', 'zhangsan', 5000); // 5秒后过期
console.log(cache.get('username')); // 'zhangsan'

setTimeout(() => {
  console.log(cache.get('username')); // null (已过期)
}, 6000);

// 示例 2: 存储对象数据
const userInfo = {
  id: 1,
  name: '张三',
  age: 25
};
cache.set('userInfo', userInfo, 60 * 60 * 1000); // 1小时后过期

// 示例 3: 永久缓存(不设置过期时间)
cache.set('theme', 'dark');
console.log(cache.get('theme')); // 'dark'

// 示例 4: 检查缓存是否存在
if (cache.has('token')) {
  console.log('用户已登录');
} else {
  console.log('请先登录');
}

// 示例 5: 清理过期缓存
cache.set('temp1', 'data1', 1000);
cache.set('temp2', 'data2', 2000);
cache.set('permanent', 'data3'); // 永久

setTimeout(() => {
  cache.clearExpired(); // 清理过期的 temp1 和 temp2
  console.log(cache.get('permanent')); // 'data3' (仍然存在)
}, 3000);

// 示例 6: 使用函数式 API
import { setCache, getCache, removeCache } from './cache';

setCache('token', 'abc123', 24 * 60 * 60 * 1000); // 24小时
const token = getCache('token');
removeCache('token');

关键点

  • 数据结构设计:将值和过期时间封装成对象存储,格式为 { value, expire }
  • 过期判断:读取时检查 Date.now() > expire,过期则自动删除并返回 null
  • 异常处理:使用 try-catch 捕获 JSON 解析和存储异常,避免程序崩溃
  • 灵活性:支持设置过期时间或永久存储(expire 为 null)
  • 类封装:使用 class 封装,支持传入不同的 storage(localStorage/sessionStorage)
  • API 完整性:提供 set、get、remove、clear、has 等完整的缓存操作方法
  • 主动清理:提供 clearExpired 方法批量清理过期缓存,优化存储空间
  • 类型支持:自动序列化和反序列化,支持存储对象、数组等复杂类型