Redo with a second stack

Step 3: Redo with a second stack

Undo needs a partner: redo. The trick is a second stack, _redo, already created for you.

The plumbing is in place. Notice that undo now snapshots the current state onto _redo before it rolls back, and backup clears _redo because starting a brand new edit means there is nothing to redo anymore.

Your job is the last piece:

  • redo() pops the most recently undone snapshot off _redo and restores it. If _redo is empty, redo does nothing.

With this in place, undo followed by redo returns you exactly to where you were. And because backup wipes _redo, taking a fresh snapshot after an undo correctly discards the old redo trail.

Hints
Starter code
class Memento:
    def __init__(self, state):
        self._state = state

    def get_state(self):
        return self._state


class Editor:
    def __init__(self):
        self.content = ""
        self._history = []
        self._redo = []

    def save(self):
        return Memento(self.content)

    def restore(self, memento):
        self.content = memento.get_state()

    def backup(self):
        self._history.append(self.save())
        self._redo = []

    def undo(self):
        if not self._history:
            return
        self._redo.append(self.save())
        memento = self._history.pop()
        self.restore(memento)

    def redo(self):
        """Restore the most recently undone snapshot (no-op if none)."""
        # TODO: if the redo stack is non-empty, pop that memento and restore it
        pass
Write it on a laptop

The editor and the test runner need a wide screen. Open this page on a desktop browser and your progress will be waiting.