Lesson 7 of 8
Undo, step by step
- 15 min
- 5 checks
- 3 hints
- Go to task
Goal
A history of snapshots that never change
Explanation
Undo looks like a complicated feature, but it follows directly from the "Don't mutate, make a copy" lesson: if every change produces a new array and leaves the old one alone, the old one stays an intact snapshot you can go back to whenever you like.
The history here is a stack. Before every change you push the current state onto past, and to undo you pop the last thing you pushed and put it back. You don't need a deep copy or any comparison, because you're only keeping references.
The trap is changing the state in place with push or splice. Then everything on the stack is a reference to the same array, so the "past" changes along with the present and there's nothing left to go back to.
Your task
Finish commit(next) so it pushes state.items onto past, puts next in its place and re-renders. Finish undo() so it restores the last snapshot from past, and make render() disable #undo when past is empty.
Checks
5 checks- The undo button follows the history: disabled, then enabled, then disabled again
- Undo reverses an addition
- Undo reverses a removal too
- Two undos in a row go back one step at a time
- The restored snapshot is the same array, not a copy of it