How would you extend a Memento-based undo implementation to also support redo?
Add a second stack, typically called something like redoHistory, alongside the existing undo history stack. Whenever undo() runs, before restoring the popped memento, push the state the object is currently in — the one being moved away from — onto the redo stack. A subsequent redo() call then pops from that redo stack and restores from it, moving the object forward again. One detail matters: any new saveState() call after a fresh edit should clear the redo stack, since redoing into a state that's no longer consistent with the edit history would be incorrect — this mirrors how undo/redo works in every real text editor, where making a new edit after an undo discards the redo trail.
Ready to master this question?
Generate a complete walkthrough — background, the full answer in plain language, a working code example explained line by line, a real-world scenario, common mistakes, and how this same question gets asked in different ways.
Sign in to generate a response