LRU cache 数据结构 Typescript 实现

发布于 2023-11-27 11:57:33 字数 1156 浏览 32 评论 0

/**
 * 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;
    }
}

屏幕截图 2022-02-15 140656

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

关于作者

知你几分

暂无简介

文章
评论
27 人气
更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文