Bound the history

Step 5: Bound the history

Real editors cannot keep every snapshot forever, or memory would grow without limit. So the history is capped at the most recent max_history snapshots.

The Editor now takes a max_history argument (already wired into init), and backup already appends the new snapshot and clears the redo stack for you.

Finish backup by enforcing the cap: after appending, if _history holds more than max_history snapshots, drop the oldest ones so only the newest max_history remain.

This is the classic memory trade-off in the Memento pattern. Snapshots are cheap to create but they accumulate, so a bounded history keeps only a sliding window of recent save points and lets the older ones fall away.

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

    def get_state(self):
        return self._state


class Editor:
    def __init__(self, max_history=100):
        self.content = ""
        self.cursor = 0
        self.max_history = max_history
        self._history = []
        self._redo = []

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

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

    def backup(self):
        """Push a snapshot, keeping at most max_history mementos."""
        self._history.append(self.save())
        self._redo = []
        # TODO: if len(self._history) exceeds max_history, drop the oldest

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

    def redo(self):
        if not self._redo:
            return
        memento = self._redo.pop()
        self.restore(memento)
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.