|
| 1 | +/* |
| 2 | +INFO: Keyed Collection in JavaScript |
| 3 | +Keyed Collection are special objects for storing collections of data using keys (like a map or a set). |
| 4 | +There are 4 types: |
| 5 | +*/ |
| 6 | + |
| 7 | +/* |
| 8 | +INFO: 1. Map |
| 9 | +Stores key-value pairs. |
| 10 | +Keys can be any type (object, string, number, etc.) |
| 11 | +Maintains insertion order |
| 12 | +*/ |
| 13 | +let collection = new Map(); |
| 14 | + |
| 15 | +collection.set("key", 100); |
| 16 | +collection.set(window, 200); |
| 17 | +collection.set(5, 300); |
| 18 | + |
| 19 | +console.log(collection.get(window)); |
| 20 | +console.log(collection.size); |
| 21 | +collection.delete(window); |
| 22 | +console.log(collection.size); |
| 23 | +collection.clear(); |
| 24 | +console.log(collection.size); |
| 25 | +console.log(collection.keys()); |
| 26 | +console.log(collection.values()); |
| 27 | + |
| 28 | +let coll = new Map([ |
| 29 | + ["key", 100], |
| 30 | + [window, 200], |
| 31 | + [5, 3], |
| 32 | +]); |
| 33 | +console.log(coll.get("key")); |
| 34 | +console.log(coll.get(window)); |
| 35 | +console.log(coll.get(5)); |
| 36 | + |
| 37 | +/* |
| 38 | +INFO: 2. WeakMap |
| 39 | +Like Map, but: |
| 40 | +Only objects as keys |
| 41 | +Keys are weakly referenced (don't prevent garbage collection) |
| 42 | +Not iterable (you can't loop through it) |
| 43 | +*/ |
| 44 | +let obj = {}; |
| 45 | +let weakMap = new WeakMap(); |
| 46 | +weakMap.set(obj, "data"); |
| 47 | + |
| 48 | +/* |
| 49 | +INFO: 3. Set |
| 50 | +A collection of unique values |
| 51 | +Can store any type of value |
| 52 | +No duplicate elements |
| 53 | +*/ |
| 54 | +let set = new Set(); |
| 55 | +set.add(1); |
| 56 | +set.add(2); |
| 57 | +set.add(1); // Duplicate, ignored |
| 58 | +console.log(set); // Set(2) {1, 2} |
| 59 | + |
| 60 | +/* |
| 61 | +INFO: WeakSet |
| 62 | +Let Set, but: |
| 63 | +Only stores objects |
| 64 | +Objects are weakly held |
| 65 | +Not iterable |
| 66 | +*/ |
| 67 | +let object = {}; |
| 68 | +let weakSet = new WeakSet(); |
| 69 | +weakSet.add(obj); |
0 commit comments