๐ JavaScript Map (HashMap) Basics
- 
Definition: A Mapstores key-value pairs and maintains insertion order.
- Key Types: Any (string, number, object, etc.).
โ Common Methods
const map = new Map();
// Add/Update
map.set('a', 1);
// Get
map.get('a'); // 1
// Check existence
map.has('a'); // true
// Delete
map.delete('a');
// Size
map.size; // 0
// Clear all
map.clear();
๐ Iterating
for (const [key, value] of map) console.log(key, value);
map.forEach((value, key) => console.log(key, value));
  
  
  ๐ Map vs Object
| Feature | Map | Object | 
|---|---|---|
| Key Types | Any | String/Symbol | 
| Order | Maintains | Unordered | 
| Iteration | Easy | Complex | 
| Performance | Better for frequent updates | Slower | 
โ
 Use Map when:  
- Keys are not just strings.
- Frequent add/remove operations.
- Need to maintain insertion order.
Javascript Code
/**
 * @param {string} ransomNote
 * @param {string} magazine
 * @return {boolean}
 */
var canConstruct = function (ransomNote, magazine) {
    let myMap = new Map();
    for (item of magazine) {
        myMap.set(item, (myMap.get(item) || 0) + 1);
    }
    for (item of ransomNote) {
        const count = myMap.get(item);
        if (!count) return false;
        myMap.set(item, count - 1);
    }
    return true
};
 

 
    
Top comments (0)