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.
All methods for WeakMap
addgethasdeletegetOrInsertgetOrInsertComputed
they are similar to methods in JS: Map.prototype
// demo of methods for WeakMap const wm = new WeakMap(); const xkey = { "hi": 3 }; // add wm.set(xkey, 1); // get console.assert(wm.get(xkey) === 1); // has console.assert(wm.has(xkey) === true); // delete wm.delete(xkey); console.assert(wm.has(xkey) === false);
demo of the auto remove keys
// demo of the auto key removal const wp = new WeakMap(); let xobj = { "hi": 1 }; wp.set(xobj, 1); console.assert(wp.get(xobj) === 1); // reset the object xobj = null; // the wp no longer has the key
why 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