4. Undo/Redo for Product Listing Filters
On a fashion store's product listing page, shoppers stack filters: category, brands, a price cap, a size. Usability tests showed that people often click the wrong chip and then lose several selections trying to recover.
The team is adding Undo and Redo buttons above the product grid. They behave like a text editor: Undo steps back through filter changes, Redo re-applies them, and any new change after an Undo discards the Redo history. Clicking a chip that is already selected must not create an empty history step. Memory on mobile is limited, so only the last historyLimit changes can be undone.
Your task:
Write the class FilterHistory. It starts with no filters.
- new FilterHistory(historyLimit)
- set(key, value): set or replace one filter. value is a string, number or array.
- remove(key): remove one filter.
- clear(): remove all filters.
- undo() and redo()
- canUndo() and canRedo(): booleans for enabling the buttons.
- getFilters(): the current filters as a plain object.
Rules:
- set, remove, clear, undo and redo return true when they changed the filters and false when they did nothing.
- A set, remove or clear that leaves the filters unchanged is ignored completely: no history step, and the Redo history is kept. Compare values by content, so ["nike"] equals ["nike"].
- Every change that is recorded clears the Redo history.
- clear is one step. Undoing it restores every filter.
- Keep at most historyLimit Undo steps. When a new change would go over the limit, forget the oldest step.
Notes: - History steps must not share objects with the current filters, or editing one will silently change the other.
What you'll write
FilterHistoryclassKeeps the filter state with undo and redo.
Examples
Example 1
- Input
const h = new FilterHistory(10)
h.set("category", "shoes")h.set("brand", ["nike"])h.undo()
h.getFilters()
- Output
h.set("category", "shoes") → trueh.set("brand", ["nike"]) → trueh.undo() → true
h.getFilters() → { category: "shoes" }
- Explanation
- Undo removes the last change (the brand).
Example 2
- Input
// continuing from example 1
h.set("priceMax", 100)h.redo()
h.canRedo()
- Output
h.set("priceMax", 100) → trueh.redo() → false
h.canRedo() → false
- Explanation
- The new priceMax change cleared the Redo history, so the brand cannot come back.
Solution
Write FilterHistory. 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.