Update CharBag

This commit is contained in:
MrLetsplay 2023-11-22 21:06:02 +01:00
parent a442e1e92a
commit aa701961c8
Signed by: mr
SSH Key Fingerprint: SHA256:92jBH80vpXyaZHjaIl47pjRq+Yt7XGTArqQg1V7hSqg
3 changed files with 31 additions and 10 deletions

View File

@ -8,15 +8,29 @@ public class ArrayCharBag implements CharBag {
private List<Char> chars = new ArrayList<>();
@Override
public void add(Char character) {
public int add(Char character) {
int i = 0;
while(Util.comparePositions(chars.get(i).position(), character.position()) < 0) i++;
// TODO: use binary search
while(i < chars.size() && Util.comparePositions(chars.get(i).position(), character.position()) < 0) i++;
chars.add(i, character);
return i;
}
@Override
public void remove(Char character) {
public int remove(Char character) {
int i = 0;
// TODO: use binary search
while(i < chars.size() && Util.comparePositions(chars.get(i).position(), character.position()) < 0) i++;
if(i == chars.size() || Util.comparePositions(chars.get(i).position(), character.position()) != 0) return -1;
chars.remove(character);
return i;
}
@Override
public String toString() {
return chars.stream()
.map(c -> c.value())
.reduce(new StringBuilder(), (b, s) -> b.append(s), (a, b) -> a.append(b)).toString();
}
}

View File

@ -1,7 +1,3 @@
package me.mrletsplay.shareclientcore.document;
public record Char(Identifier[] position, int lamport, String value) {
}
public record Char(Identifier[] position, int lamport, String value) {}

View File

@ -6,7 +6,18 @@ public interface CharBag {
// public Character findBefore(PositionIdentifier position);
// public Character findAfter(PositionIdentifier position);
public void add(Char character);
public void remove(Char character);
/**
* Adds a character to the bag and returns the index it was inserted at
* @param character The character to add
* @return The index it was inserted at
*/
public int add(Char character);
/**
* Removes a character from the bag and returns the index it was located at, or -1 if it was not contained in the bag
* @param character The character to remove
* @return The index it was located at
*/
public int remove(Char character);
}