Text Buffer With Undo and Redo
Implement a class TextBuffer that holds a piece of text and can undo and redo its edits. There are two kinds of edit: appending to the end and deleting from the end. Write these methods:
TextBuffer()starts with empty text and nothing to undo or redo.append(s)addssto the end of the text. Returns the length of the text afterwards.delete_last(k)deletes the lastkcharacters, or all of them if the text is shorter thank, and returns the deleted characters. If the text is already empty, it returns""and does nothing at all: it is not an edit, so it does not change what can be undone or redone.undo_edit()takes back the most recent edit that has not been undone, so the text is what it was just before that edit. Returns the text afterwards. If there is nothing to undo, nothing changes and it returns the current text.redo_edit()puts back the edit that was undone most recently. Returns the text afterwards. If there is nothing to redo, nothing changes and it returns the current text.get_text()returns the current text.
Making a new edit throws away every edit that could still be redone. The tests call the methods in sequence and compare every return value. The expected list holds null for the constructor.
Example 1
TextBuffer()
append("ab") returns 2
append("cd") returns 4
delete_last(3) returns "bcd"
undo_edit() returns "abcd"
undo_edit() returns "ab"
redo_edit() returns "abcd"
append("x") returns 5
redo_edit() returns "abcdx"
undo_edit() returns "abcd"
The delete removes bcd. Two undos go back to abcd and then ab, and the redo brings abcd back. Appending x is a new edit, so the undone delete can no longer be redone; the last undo removes the x.
Constraints
sis1to5lowercase letters, and the text never grows past60characters.1 <= k <= 6- Each test makes
1to40method calls after the constructor.
Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.