Shenglian / -WORK_TIP

工作上小技巧
4 stars 1 forks source link

[js] 其中一種複寫原生的方式 #184

Open Shenglian opened 4 years ago

Shenglian commented 4 years ago
module.exports = class Cache extends Map {
  constructor() {
    super();
    this.timeout = 1000;
  }
  set(key, value) {
    super.set(key, {
      tid: setTimeout(this.delete.bind(this, key), this.timeout),
      value,
    });
  }
  get(key) {
    let entry = super.get(key);
    if (entry) {
      return entry.value;
    }
  }
  delete(key) {
    let entry = super.get(key);
    if (entry) {
      clearTimeout(entry.tid);
      super.delete(key);
    }
  }
  clear() {
    for (let entry of this.values()) {
      clearTimeout(entry.tid);
    }
    super.clear();
  }
};
Shenglian commented 4 years ago

https://github.com/fent/node-ytdl-core/blob/master/lib/cache.js