当不再有任何引用时从 Map 中删除值

问题描述

当 Maps 值不再有任何引用时,我想从 Map 中删除一个值。我设计了这个类,想知道这是否是正确的方法

class WeakRefMap {
    constructor() {
        super()
        this.map = new Map()
        this.registry = new FinalizationRegistry(key => this.delete(key))
    }

    add(key,value) {
        const object = new WeakRef(value)

        this.registry.register(object,key)

        this.map.add(key,object)
        
        return object
    }

    delete(key) {
        const object = this.map.get(key)

        this.registry.unregister(object)

        this.map.delete(key)
    }

    get(key) {
        return this.map.get(key).deref()
    }
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)