Memento
TypeScriptApplicationMemento in TypeScript
Captures editor content snapshots so a history manager can restore earlier document states without exposing editor internals.
TypeScript
class EditorMemento {
constructor(readonly content: string) {}
}
class TextEditor {
private content = "";
write(text: string) {
this.content = text;
}
createMemento() {
return new EditorMemento(this.content);
}
restore(memento: EditorMemento) {
this.content = memento.content;
}
print() {
console.log(this.content);
}
}
class History {
private readonly snapshots: EditorMemento[] = [];
save(memento: EditorMemento) {
this.snapshots.push(memento);
}
undo(): EditorMemento | undefined {
return this.snapshots.pop();
}
}
const editor = new TextEditor();
const history = new History();
editor.write("Draft version");
history.save(editor.createMemento());
editor.write("Published version");
editor.print();
const previousVersion = history.undo();
if (previousVersion) {
editor.restore(previousVersion);
}
editor.print();