LRU cache 数据结构 Typescript 实现
/** * Nodejs 原生的 Map 结构本身就是由链表和哈希表构造而成, * Map set 操作默认放到链表队尾,即最近使用的数据放到队尾 * 最不常用的数据放到队头,get 操作先 delete, 再 set 表示 * 将数据移动到队尾 */ export class LRUCache<K, V> { private readonly max: number; private readonly cache: Map<K, V>; constructor(max = 100) { this.max = max; this.cache = new Map<K, V>(); } get(key: K): V | undefined { const item = this.cache.get(key); if (item) { this.cache.delete(key); this.cache.set(key, item); } return item; } set(key: K, val: V) { if (this.cache.has(key)) { this.cache.delete(key); } else if (this.cache.size >= this.max) { this.cache.delete(this.first()); } this.cache.set(key, val); } first() { return this.cache.keys().next().value; } }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论