LRU 缓存算法基于一个基本假设:如果一个数据长时间没有被访问,那么它未来也很可能不会再被访问。因此,当缓存达到上限时,应该淘汰掉最久未被访问的数据。
class LRUCache {constructor(maxSize, maxAge) {//缓存数量this.maxSize = maxSize;//缓存毫秒数this.maxAge = maxAge;this.cache = new Map();this.timer = null;}/*** 判断缓存key是否过期,过期则删除* 未过期的缓存,延长寿命*/get(key) {const item = this.cache.get(key);if (item) {clearTimeout(item.timer);const now = new Date().getTime();//判断缓存是否过期if (now - item.timestamp > this.maxAge) {this.cache.delete(key);return undefined;}//重新记录过期时间this.cache.delete(key);this.cache.set(key, { value: item.value, timestamp: now, timer: setTimeout(() => this.cache.delete(key), this.maxAge) });return item.value;}return undefined;}/** * 缓存大小超出限制时删除最旧的缓存。(即最先插入的)* 缓存数据时,用计时器实现自动过期逻辑*/set(key, value) {const now = new Date().getTime();if (this.cache.size >= this.maxSize) {const oldestKey = this.cache.keys().next().value;this.cache.delete(oldestKey);}this.cache.set(key, { value, timestamp: now, timer: setTimeout(() => this.cache.delete(key), this.maxAge) });}clear() {this.cache.clear();}}