048
LVL 02 — CIRCUIT BREAKER SESSION 048 DAY 48

HASH MAPS

🎫 PIXELCRAFT-036
Feature | 🟡 Medium | Priority: 🟡 Medium

Users want a "recently used colors" palette. Also, reapplying the same filter to the same image should be instant (don't recompute). Both need fast lookups.
CONCEPTS.UNLOCKED
#
Hash Maps
Key → value in O(1) average time. Given any key, find its value instantly. No searching, no iteration. The closest thing to magic in computer science.
🗺
JavaScript Map vs Objects
Map supports any key type, preserves insertion order, has .size, and is optimized for frequent additions/deletions. Plain objects are simpler but keys must be strings.
How Hashing Works
key → hash function → array index. The hash function converts any key into a number, which becomes an array index. Lookup is one computation + one array access = O(1).
💥
Hash Collisions
Two different keys hash to the same index. Resolved by chaining (linked list at each index) or open addressing (probe for next empty slot). Good hash functions minimize collisions.
📦
LRU Cache
Least Recently Used eviction: when the cache is full, remove the item that hasn't been accessed the longest. Keeps frequently used items hot. Used by browsers, databases, CDNs.
🔄
Cache Invalidation
When to clear/update the cache. "There are only two hard things in CS: cache invalidation and naming things." If the source changes, the cache must be updated or cleared.
HANDS-ON.TASKS
01
Build a Recent Colors Tracker
class RecentColors { constructor(maxSize = 20) { this.colors = new Map(); // hex → { count, lastUsed } this.maxSize = maxSize; } add(hex) { if (this.colors.has(hex)) { const entry = this.colors.get(hex); entry.count++; entry.lastUsed = Date.now(); } else { if (this.colors.size >= this.maxSize) { // Evict least recently used let oldest = null; for (const [key, val] of this.colors) { if (!oldest || val.lastUsed < oldest.lastUsed) oldest = { key, ...val }; } this.colors.delete(oldest.key); } this.colors.set(hex, { count: 1, lastUsed: Date.now() }); } } getRecent(n = 10) { return [...this.colors.entries()] .sort((a, b) => b[1].lastUsed - a[1].lastUsed) .slice(0, n) .map(([hex]) => hex); } }
02
Build a Filter Result Cache
class FilterCache { constructor(maxEntries = 50) { this.cache = new Map(); this.maxEntries = maxEntries; } getCacheKey(imageId, filterName, filterValue) { return `${imageId}:${filterName}:${filterValue}`; } get(imageId, filterName, filterValue) { const key = this.getCacheKey( imageId, filterName, filterValue); return this.cache.get(key) || null; } set(imageId, filterName, filterValue, resultData) { const key = this.getCacheKey( imageId, filterName, filterValue); if (this.cache.size >= this.maxEntries) { const firstKey = this.cache.keys().next().value; this.cache.delete(firstKey); } this.cache.set(key, resultData); } }
03
Wire Cache to PixelCraft

Before applying a filter, check the cache. Cache hit = instant.

ScenarioTime
First application200ms
Cached (same filter + value)0ms
04
Build the ColorPalette Component

Build a <ColorPalette> component showing recent and frequent colors. Each swatch is clickable, most recent on top. Track usage with the RecentColors class.

05
Close the Ticket
git switch -c feature/PIXELCRAFT-036-hash-cache git add src/ git commit -m "Add color palette + filter cache with hash maps (PIXELCRAFT-036)" git push origin feature/PIXELCRAFT-036-hash-cache # PR → Review → Merge → Close ticket ✅
CS.DEEP-DIVE

Hash tables are arguably the most important data structure in practical software engineering.

O(1) average lookup is the closest thing to magic in CS.

// Every language has them:

JavaScript  → Object / Map
Python      → dict
Java        → HashMap
C#          → Dictionary

// Hash tables power:
Database indexes, caches (Redis, Memcached),
DNS resolution, routing tables,
symbol tables in compilers,
and the JavaScript object system itself.
"Cache Everything"
[A] Implement a proper LRU cache using a Map + doubly linked list (Map for O(1) lookup, list for O(1) eviction). This is the classic LeetCode #146 problem.
[B] Add a "Favorites" color palette: starred colors persist across sessions using your useLocalStorage hook. Combine the Map with localStorage.
[C] Add cache stats in the UI: "Cache size: 23/50 | Hit rate: 67% | Memory: 12MB". Measure how much time the cache saves over a typical editing session.
REF.MATERIAL
VIDEO
CS50 / Harvard
Visual explanation: hash functions, array indexing, collisions, chaining, and why hash maps are O(1) on average.
HASH MAPCS50ESSENTIAL
ARTICLE
Mozilla Developer Network
Complete Map reference: constructor, set/get/has/delete, iteration, size, and comparison with plain objects.
MAPMDNREFERENCE
VIDEO
Fireship
Rapid overview: how hashing works, collision handling, O(1) average time, and real-world applications.
HASH TABLEQUICK
ARTICLE
Wikipedia
Theory: hash functions, collision resolution (chaining, open addressing), load factor, amortized analysis, and applications.
HASH TABLETHEORYCS
ARTICLE
Wikipedia
Cache eviction strategies: LRU, LFU, FIFO, and when each is appropriate. The theory behind every cache from browsers to databases.
LRUCACHINGTHEORY
// LEAVE EXCITED BECAUSE
Filter re-application went from 200ms to 0ms with caching. The color palette tracks favorites automatically. Hash maps turned two features that seemed complex into simple lookups.