JS: WeakMap
What is weakmap
WeakMap is similar to the Map Object, with 3 exceptions:
- Keys can only be Object Type, or unregistered Symbol type (meaning, symbols user created, not builtin symbols.).
- If a object in the key is not used elsewehere in your program, or no longer used, that key entry is deleted automatically.
- Weakmap cannot be iterated over, nor get its keys, nor looped over, nor get its item count, nor clear all.
Methods for weakmap
setgetgetOrInsertgetOrInsertComputedhasdelete
they are similar to methods in Map.prototype
- JS: Map.prototype.set
- JS: Map.prototype.get
- JS: Map.prototype.getOrInsert
- JS: Map.prototype.getOrInsertComputed
- JS: Map.prototype.has
- JS: Map.prototype.delete
// demo of methods for WeakMap const weakm = new WeakMap(); const xkey = { dog: 3 }; // set weakm.set(xkey, 1); // get console.assert(weakm.get(xkey) === 1); // has console.assert(weakm.has(xkey)); // delete weakm.delete(xkey); console.assert(weakm.has(xkey) === false);
Demo of the auto remove keys
// demo of the auto key removal const xweak = new WeakMap(); let xobj = { dog: 1 }; xweak.set(xobj, 1); console.assert(xweak.get(xobj) === 1); // reset the object xobj = null; // the xweak no longer has the key console.assert(xweak.get(xobj) === undefined);
What is the use of weakmap
// this shows the situation that WeakMap was invented // create a map const xmap = new Map(); // create a array of objects, e.g. [ { k: 0 }, { k: 1 }, { k: 2 }, { k: 3 } ] let xar = Array.from((Array(4)).keys(), (x) => ({ "k": x })); // add them all to map xar.forEach((x) => { xmap.set(x, 1); }); console.log(xmap.size); // 4 // delete our array xar = null; // the map now contain objects that wont go away, and there is no reference handle to them except iterating this map console.log(xmap.size); // 4