Computer >> Computer tutorials >  >> Programming >> Javascript

What is the use of .clear() method in Javascript weakMap?


The clear method on weakMap removes all key/value pairs from the WeakMap object.

This method has been removed from the spec and can be added back by wrapping the WeakMap object with added support for clear method.

Example

class ClearableWeakMap {
   constructor(init) {
      this._wm = new WeakMap(init)
   }
   clear() {
      this._wm = new WeakMap()
   }
   delete(k) {
   return this._wm.delete(k)
   }
   get(k) {
      return this._wm.get(k)
   }
   has(k) {
      return this._wm.has(k)
   }
   set(k, v) {
      this._wm.set(k, v)
   return this
   }
}