Created
January 7, 2021 12:51
-
-
Save le0nidas/8941cb4df909bc86fcb8be98d7f3aed2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public final class Editor { | |
private final List<String> text; | |
private int caretPosition; | |
public Editor() { | |
this.text = new ArrayList<>(); | |
this.caretPosition = 0; | |
} | |
public void write(final String sentence) { | |
text.add(sentence); | |
caretPosition = calculateCaretPositionInEndOf(text); | |
} | |
public void edit(final int index, final String newSentence) { | |
text.remove(index); | |
text.add(index, newSentence); | |
final List<String> subText = text.subList(0, index + 1); | |
caretPosition = calculateCaretPositionInEndOf(subText); | |
} | |
public void delete(final int index) { | |
final List<String> subText = new ArrayList<>(text.subList(0, index)); | |
text.remove(index); | |
caretPosition = calculateCaretPositionInEndOf(subText); | |
} | |
public void render(final Screen screen) { | |
final String allText = String.join("", text); | |
screen.render(allText); | |
screen.renderCaretAt(caretPosition); | |
} | |
public Memento backup() { | |
return new Memento(text, caretPosition); | |
} | |
public void restore(final Memento memento) { | |
text.clear(); | |
text.addAll(memento.text); | |
caretPosition = memento.caretPosition; | |
} | |
private int calculateCaretPositionInEndOf(final List<String> lines) { | |
return lines.stream().mapToInt(String::length).sum() + 1; | |
} | |
public static final class Memento { | |
private final List<String> text; | |
private final int caretPosition; | |
public Memento(List<String> text, int caretPosition) { | |
this.text = new ArrayList<>(text); | |
this.caretPosition = caretPosition; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment