2. Recently Viewed Products
A product details page shows a "Recently viewed" strip under the photo gallery. The browser keeps the raw list of product ids the shopper opened during this session, oldest first, with repeats.
The strip must show the most recent products first, show each product once, never show the product that is currently on screen, and show at most limit cards.
Your task:
Write getRecentlyViewed(viewHistory, currentProductId, limit) and return the product ids to show, in order.
Rules:
- Most recent first. If a product was viewed several times, its latest view decides its position.
- Exclude currentProductId before cutting the list to limit, so the strip is still full when the current product was among the recent ones.
- A limit of 0 returns [].
Examples
Example 1
- Input
viewHistory = ["p1", "p2", "p3", "p2", "p4"]
currentProductId = "p4"
limit = 3
- Output
["p2", "p3", "p1"]
- Explanation
- Newest first is p4, p2, p3, p1. p4 is on screen, so it is skipped.
Solution
Write getRecentlyViewed. Tab indents (Esc then Tab leaves the editor), Ctrl/⌘ + Enter runs. Each run has a 3-second limit. Your code is saved in this browser.
Test Results
Click "Run Code" to test your solution.