| 1 | --- |
| 2 | title: Build Index Maps for Repeated Lookups |
| 3 | impact: LOW-MEDIUM |
| 4 | impactDescription: 1M ops to 2K ops |
| 5 | tags: javascript, map, indexing, optimization, performance |
| 6 | --- |
| 7 | |
| 8 | ## Build Index Maps for Repeated Lookups |
| 9 | |
| 10 | Multiple `.find()` calls by the same key should use a Map. |
| 11 | |
| 12 | **Incorrect (O(n) per lookup):** |
| 13 | |
| 14 | ```typescript |
| 15 | function processOrders(orders: Order[], users: User[]) { |
| 16 | return orders.map(order => ({ |
| 17 | ...order, |
| 18 | user: users.find(u => u.id === order.userId) |
| 19 | })) |
| 20 | } |
| 21 | ``` |
| 22 | |
| 23 | **Correct (O(1) per lookup):** |
| 24 | |
| 25 | ```typescript |
| 26 | function processOrders(orders: Order[], users: User[]) { |
| 27 | const userById = new Map(users.map(u => [u.id, u])) |
| 28 | |
| 29 | return orders.map(order => ({ |
| 30 | ...order, |
| 31 | user: userById.get(order.userId) |
| 32 | })) |
| 33 | } |
| 34 | ``` |
| 35 | |
| 36 | Build map once (O(n)), then all lookups are O(1). |
| 37 | For 1000 orders × 1000 users: 1M ops → 2K ops. |
| 38 |