-
Notifications
You must be signed in to change notification settings - Fork 67
/
Copy pathtextUndoRedo.js
48 lines (40 loc) · 1023 Bytes
/
textUndoRedo.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
class TextEditor {
constructor() {
this.text = '';
this.undoStack = [];
this.redoStack = [];
}
setText(text) {
this.text = text;
}
insertText(addedText) {
this.undoStack.push(this.text);
this.text += addedText;
this.redoStack = [];
}
deleteText(deletedText) {
this.undoStack.push(this.text);
this.text = text.replace(deletedText, '')
this.redoStack = [];
}
undo() {
if(this.undoStack.length > 0){
const previousText = this.undoStack.pop();
this.redoStack.push(this.text);
this.text = previousText;
}
}
redo() {
if(this.redoStack.length){
const nextText = this.redoStack.pop();
this.undoStack.push(this.text)
this.text = nextText;
}
}
}
const editor = new TextEditor();
editor.setText('hf,tk,pk,ol')
console.log(editor.getText());
editor.insertText('aa')
editor.undo()
editor.redo();