Typorithm · medium

Undo / Redo

undo-redoproblem-labstackhistorycommand
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Undo / Redo

0%

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.

01

Undo stack holds reversible history newest-on-top.

02

Undo pops to redo; redo pops back to undo.

03

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);
  }
}

Read the implementation

Connect each part of the code to the concept before you type.

1. Two stacks

One stack holds the history to undo, the other holds undone commands ready to redo.

this.undoStack = [];
    this.redoStack = [];

2. Record action

Every new command is pushed onto the undo stack as the newest reversible step.

this.undoStack.push(command);

3. Clear redo

A fresh action invalidates the redo future, so the redo stack is emptied.

this.redoStack = [];

4. Undo move

Undo pops the newest command off undo and pushes it onto redo.

const command = this.undoStack.pop();
    this.redoStack.push(command);

5. Redo move

Redo reverses the move: pop from redo, push back onto undo.

const command = this.redoStack.pop();
    this.undoStack.push(command);

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Undo / Redo: Lesson & Practice · Typorithm | ApplyDjinn