From fb18863ed2be455ad5e91167eb8fe70aacbadc1c Mon Sep 17 00:00:00 2001 From: MrLetsplay Date: Fri, 24 Nov 2023 07:47:35 +0100 Subject: [PATCH] Add Document#localDelete --- .../shareclientcore/document/Document.java | 19 +++++++++++++++++++ .../shareclientcore/DocumentTest.java | 17 +++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/src/main/java/me/mrletsplay/shareclientcore/document/Document.java b/src/main/java/me/mrletsplay/shareclientcore/document/Document.java index 047d44a..77c882d 100644 --- a/src/main/java/me/mrletsplay/shareclientcore/document/Document.java +++ b/src/main/java/me/mrletsplay/shareclientcore/document/Document.java @@ -14,6 +14,11 @@ public class Document { this.site = site; } + /** + * Inserts characters into the document at the specified index + * @param index The index to insert at + * @param str The string to insert + */ public void localInsert(int index, String str) { if(index < 0 || index >= charBag.size() - 1) throw new IllegalArgumentException("Index out of bounds"); @@ -29,6 +34,20 @@ public class Document { } } + /** + * Deletes n characters from a document, starting at the specified index + * @param index The index to start deleting at + * @param n The number of characters to delete + */ + public void localDelete(int index, int n) { + if(index < 0 || index + n >= charBag.size() - 1) throw new IllegalArgumentException("Index out of bounds"); + + while(n-- > 0) { + // TODO: more efficient implementation (e.g. range delete in CharBag) + charBag.remove(charBag.get(index + 1)); + } + } + public CharBag getCharBag() { return charBag; } diff --git a/src/test/java/me/mrletsplay/shareclientcore/DocumentTest.java b/src/test/java/me/mrletsplay/shareclientcore/DocumentTest.java index 385acc0..d319b47 100644 --- a/src/test/java/me/mrletsplay/shareclientcore/DocumentTest.java +++ b/src/test/java/me/mrletsplay/shareclientcore/DocumentTest.java @@ -28,4 +28,21 @@ public class DocumentTest { assertThrows(IllegalArgumentException.class, () -> doc.localInsert(6, "Test")); } + @Test + public void testLocalDelete() { + Document doc = new Document(1); + doc.localInsert(0, "Hello World!"); + doc.localDelete(5, 6); + assertEquals("Hello!", doc.getContents()); + } + + @Test + public void testLocalDeleteInvalidIndexFails() { + Document doc = new Document(1); + doc.localInsert(0, "Hello World!"); + assertThrows(IllegalArgumentException.class, () -> doc.localDelete(-1, 10)); + assertThrows(IllegalArgumentException.class, () -> doc.localDelete(12, 1)); + assertThrows(IllegalArgumentException.class, () -> doc.localDelete(0, 13)); + } + }