1. Two stacks
One stack holds the history to undo, the other holds undone commands ready to redo.
this.undoStack = [];
this.redoStack = [];Typorithm · medium
Step 1 of 8 · intro card
Applied Patterns
An editor's undo/redo is two stacks. New actions push onto the undo stack and clear the redo stack; undo pops a command to the redo stack; redo pops it back to undo. LIFO order naturally walks history backward and forward.
A text editor needs undo and redo: undo reverses the most recent action, redo re-applies the last thing you undid, and a brand-new action discards any pending redo future.
The two-stacks pattern stores history as an undo stack and a redo stack. Doing a command pushes it onto undo and clears redo, because the future you could have redone no longer applies.
Undo pops the newest command off undo and pushes it onto redo; redo does the mirror image. LIFO ordering means the newest action is always the one reversed first.
Undo stack holds reversible history newest-on-top.
Undo pops to redo; redo pops back to undo.
A new action clears the redo stack.
class Editor {
constructor() {
this.undoStack = [];
this.redoStack = [];
}
do(command) {
this.undoStack.push(command);
this.redoStack = [];
}
undo() {
if (!this.undoStack.length) return;
const command = this.undoStack.pop();
this.redoStack.push(command);
}
redo() {
if (!this.redoStack.length) return;
const command = this.redoStack.pop();
this.undoStack.push(command);
}
}Connect each part of the code to the concept before you type.
One stack holds the history to undo, the other holds undone commands ready to redo.
this.undoStack = [];
this.redoStack = [];Every new command is pushed onto the undo stack as the newest reversible step.
this.undoStack.push(command);A fresh action invalidates the redo future, so the redo stack is emptied.
this.redoStack = [];Undo pops the newest command off undo and pushes it onto redo.
const command = this.undoStack.pop();
this.redoStack.push(command);Redo reverses the move: pop from redo, push back onto undo.
const command = this.redoStack.pop();
this.undoStack.push(command);Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.