Skip to the solution
MediumFrontend6 min read

Build an Undo/Redo Command Stack for a Text Editor

1.0k views

The problem

Problem, as an interviewer would state it: "Implement an undo/redo system for a text editor using the Command pattern — each edit is an object with do() and undo() methods, and the system needs to support a real, deep undo/redo history."

Examples:

Code
stack.execute(insertCommand("Hello", 0));
stack.undo(); // reverts the insert
stack.redo(); // re-applies it

Clarifying questions expected:

  • What should happen to the redo history if a NEW action is performed after an undo — is it cleared, or preserved as a branch?
  • Does the command need to store enough information to undo itself, or does the stack manage that separately?
  • Is there a maximum history depth, or unbounded?

Code / implementation expected: Yes — real, direct proof of a real sequence of inserts, undos, and redos, including the critical case of a new action correctly clearing the redo stack.

  • command-pattern
  • stack
  • editor

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

6 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: the undo/redo command stack correctly handles a real sequence of inserts and undos, and clears the redo history after a new action

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 91 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextMedium

Async reduce utility

Continue