๐Ÿ—บ๏ธ

JavaScript Maps

Store key-value pairs with the Map data structure

โญ Data Structure

What are Maps?

Maps are collections of key-value pairs where keys can be any type (not just strings like objects). Perfect for tracking pantry inventory, ingredient quantities, or menu item prices!

๐Ÿ’ก Real-World Example:

Track how much of each ingredient you have: Map { "flour" => 500, "sugar" => 300, "eggs" => 12 }

Working with Maps

1. Creating and Adding to Maps

const pantry = new Map();
pantry.set("flour", 500);    // Add key-value pair
pantry.set("sugar", 300);
pantry.set("eggs", 12);
console.log(pantry.size);    // 3

2. Getting Values

console.log(pantry.get("flour"));  // 500
console.log(pantry.has("sugar"));  // true
console.log(pantry.has("milk"));   // false

3. Updating and Deleting

pantry.set("flour", 450);   // Update existing
pantry.delete("eggs");      // Remove key-value pair
pantry.clear();             // Remove all entries

4. Iterating Over Maps

const menu = new Map([
    ["pasta", 12],
    ["pizza", 15],
    ["salad", 8]
]);

for (const [dish, price] of menu) {
    console.log(`${dish}: $${price}`);
}

5. Map vs Object

// Maps: Any type as key, easy iteration, size property
// Objects: String keys only, more common, simpler syntax

const map = new Map();
map.set(1, "one");        // Number key OK!
map.set(true, "yes");     // Boolean key OK!

Learn More

๐Ÿš€ Try It Yourself

Output:

๐Ÿช

Game 1: Pantry Map System

Manage a kitchen pantry using Maps! Add, update, and track ingredient quantities with efficient lookups.

โž• Add to Pantry

๐Ÿ“ฆ Pantry Inventory (0 items)

๐Ÿ”Ž

Game 2: Stock Lookup Game

Practice fast lookups with Maps! Search for items and update stock levels efficiently.

๐ŸŽฎ Quick Lookup Challenge

โฑ๏ธ Performance Stats:
Lookups performed: 0
Items found: 0
Average time: 0ms

๐Ÿ“Š Stock Adjustment

๐Ÿช

Challenge 1: Pantry Map System

๐Ÿ“‹ Your Mission:

Create a pantry inventory system:

  1. Create a Map and add multiple items with quantities
  2. Update an existing item's quantity
  3. Return total number of different items and specific item quantity

Example:

managePantry([["flour", 500], ["sugar", 300]], "flour", 450)

โ†’ { totalItems: 2, flourQuantity: 450 }

๐Ÿ’ก Hints:

  • Create Map from array: new Map(items)
  • Use .set() to update
  • Use .size and .get()

Test Results:

๐Ÿ”

Challenge 2: Stock Lookup Game

๐Ÿ“‹ Your Mission:

Check if items are in stock and get their quantities:

  1. Create a Map from inventory data
  2. Check which items from a search list are in stock
  3. Return array of items that are in stock

Example:

checkStock([["eggs", 12], ["milk", 2]], ["eggs", "bread", "milk"])

โ†’ ["eggs", "milk"] (bread not in stock)

๐Ÿ’ก Hints:

  • Create Map from inventory
  • Use .filter() on searchItems
  • Check with map.has(item)

Test Results: