Add Document#localDelete

This commit is contained in:
MrLetsplay 2023-11-24 07:47:35 +01:00
parent 788ae0f364
commit fb18863ed2
Signed by: mr
SSH Key Fingerprint: SHA256:0zWNiRisbQ4dq/CCQAaMLoF3UfkF5wKPXO7DcjfFBEU
2 changed files with 36 additions and 0 deletions

View File

@ -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;
}

View File

@ -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));
}
}