Lesson 6 of 8
Fast lookup by ID
- 13 min
- 5 checks
- 3 hints
- Go to task
Goal
Build the index once, then look up in one step
Explanation
Each order has a user ID, and you want that user's name. If you write users.find(u => u.id === order.userId) inside the loop over the orders, the code walks the whole user list for every single order, and four thousand orders with four thousand users means millions of comparisons.
The fix is to build an index once with new Map(users.map(u => [u.id, u])), so every lookup with get takes a single step no matter how long the list is. The same goes for the question "is this in the list?": instead of includes inside the loop, use a Set with has.
Watch out: a Map takes the key's type into account, so get('7') won't find the key 7. IDs that come from dataset or from the URL are always strings, so convert them to numbers with Number before you look them up.
Your task
Rewrite withNames(orders, users) to use a Map index and withoutBlocked(orders, blockedIds) to use a Set, so the results stay the same and each list is read only once. If an order's user isn't in the user list, set the name to 'Unknown', just like the current code does.
Checks
5 checks- withNames adds the right name
- A missing user gets the name "Unknown"
- The user list is read once, not for every order
- withoutBlocked drops the orders of blocked users
- The block list is read once, not for every order