Every undoable action in an editor is a Command: an object that knows how to do something and how to undo it. Bundling the action and its inverse together is what makes undo possible later. The editor never needs to know the details.
The document is a tiny object holding a string. Implement the first concrete command, Insert.
Insert(pos, text): execute(doc) inserts text into doc.text at index pos; undo(doc) removes exactly those characters againclass Document:
def __init__(self, text=""):
self.text = text
class Command:
def execute(self, doc):
raise NotImplementedError
def undo(self, doc):
raise NotImplementedError
class Insert(Command):
def __init__(self, pos, text):
self.pos = pos
self.text = text
def execute(self, doc):
"""Insert self.text into doc.text at self.pos."""
# TODO: doc.text = doc.text[:self.pos] + self.text + doc.text[self.pos:]
pass
def undo(self, doc):
"""Remove the characters this command inserted."""
# TODO: doc.text = doc.text[:self.pos] + doc.text[self.pos + len(self.text):]
pass
The editor and the test runner need a wide screen. Open this page on a desktop browser and your progress will be waiting.
Every undoable action in an editor is a Command: an object that knows how to do something and how to undo it. Bundling the action and its inverse together is what makes undo possible later. The editor never needs to know the details.
The document is a tiny object holding a string. Implement the first concrete command, Insert.
Insert(pos, text): execute(doc) inserts text into doc.text at index pos; undo(doc) removes exactly those characters againPress Run Tests or ββ© to check your solution.