javascript / intermediate
Snippet
Efficient Key-Value Storage with Map
The Map object is a collection of keyed data items, similar to an Object. However, Maps allow keys of any type (including objects), maintain insertion order, and offer better performance for frequent additions/removals.
snippet.js
1
2
3
4
5
const registry = new Map();const keyObj = { id: 1 };registry.set(keyObj, 'Metadata for Object 1');console.log(registry.get(keyObj));console.log(registry.size);
Breakdown
1
registry.set(keyObj, 'Metadata for Object 1');
Uses an actual object reference as a unique key in the map.
2
registry.size;
Directly provides the number of elements, unlike objects which require manual iteration or Object.keys().