Skip to content

Instantly share code, notes, and snippets.

@zgover
Last active April 23, 2021 16:57
Show Gist options
  • Save zgover/55d82cb6a77212d2788e4d741e712866 to your computer and use it in GitHub Desktop.
Save zgover/55d82cb6a77212d2788e4d741e712866 to your computer and use it in GitHub Desktop.
[JS/TS Clearable WeakMap] JS/TS – Implementing a clearable WeakMap-like class #javascript #weakmap #class #constructor #garbagecollection #memory #references #private #typescript
class ClearableWeakMap<T = unknown, K extends object = object> {
  private _: WeakMap<K,T>;
  constructor(init: Iterable<[K,T]>) {
    this._ = new WeakMap(init)
  }
  clear() {
    this._ = new WeakMap()
    return this
  }
  delete(k: K) {
    return this._.delete(k)
  }
  get(k: K) {
    return this._.get(k)
  }
  has(k: K) {
    return this._.has(k)
  }
  set(k: K, v: T) {
    this._.set(k, v);
    return this
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment