Build challenges · 4 steps · javascript · python
Command — Undo & Redo
Make every change an object that knows how to take itself back.
Undo is the feature that looks trivial and is not. The obvious approach — snapshot the whole document after every keystroke — works until the document is large, and then it is a memory leak with a keyboard shortcut.
The Command pattern inverts it. Instead of remembering states, you remember changes, and you make each change an object that knows two things: how to do itself, and how to take itself back. The history then needs to know nothing about documents at all — it is two stacks and a loop.
You will build it across four steps:
- commands that apply themselves
- commands that revert themselves, and an undo stack
- redo — the undo stack read backwards
- the bug every first implementation has: what happens to redo when you undo, then type something new
Two editable files, and the split is the point. When you are done, open
history.js and notice it never mentions a string.
The workspace
These files carry across every step. What you write in one step is what you start the next with.
- commands.js
- history.js
- harness.jsread-only
Start anywhere. Open step 3 first and you are handed the reference build of steps 1 and 2, so every step stands on its own. Nothing here is locked behind anything else.
This build applies Stacks & Queues. Read the lesson first if it is unfamiliar — a recommendation, not a prerequisite.