Skip to content

Commit

Permalink
Improve Array and Map API (#27)
Browse files Browse the repository at this point in the history
  • Loading branch information
davidbrochart authored Nov 7, 2023
1 parent 7de2731 commit 89d4b85
Show file tree
Hide file tree
Showing 4 changed files with 51 additions and 0 deletions.
9 changes: 9 additions & 0 deletions python/pycrdt/array.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,15 @@ def extend(self, value: list[Any]) -> None:
def clear(self) -> None:
del self[:]

def insert(self, index, object) -> None:
self[index:index] = [object]

def pop(self, index: int = -1) -> Any:
with self.doc.transaction():
res = self[index]
del self[index]
return res

def __add__(self, value: list[Any]) -> Array:
with self.doc.transaction():
length = len(self)
Expand Down
12 changes: 12 additions & 0 deletions python/pycrdt/map.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,18 @@ def get(self, key: str, default_value: Any | None = None) -> Any | None:
return self[key]
return default_value

def pop(self, key: str, default_value: Any | None = None) -> Any:
with self.doc.transaction():
if key not in self.keys():
if (
default_value is None
): # FIXME: how to know if default_value was passed?
raise KeyError
return default_value
res = self[key]
del self[key]
return res

def keys(self):
with self.doc.transaction() as txn:
return iter(self.integrated.keys(txn))
Expand Down
19 changes: 19 additions & 0 deletions tests/test_array.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,3 +109,22 @@ def callback(e):
assert sid1 == "o_1"
assert sid2 == "od0"
assert sid3 == "od1"


def test_api():
# pop
doc = Doc()
array = Array([1, 2, 3])
doc["array"] = array
v = array.pop()
assert v == 3
v = array.pop(0)
assert v == 1
assert str(array) == "[2]"

# insert
doc = Doc()
array = Array([1, 2, 3])
doc["array"] = array
array.insert(1, 4)
assert str(array) == "[1,4,2,3]"
11 changes: 11 additions & 0 deletions tests/test_map.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,3 +45,14 @@ def test_api():
assert dict(map0.items()) == items
map0.clear()
assert len(map0) == 0

# pop
doc = Doc()
map0 = Map({"foo": 1, "bar": 2})
doc["map0"] = map0
v = map0.pop("foo")
assert v == 1
assert str(map0) == '{"bar":2}'
v = map0.pop("bar")
assert v == 2
assert str(map0) == "{}"

0 comments on commit 89d4b85

Please sign in to comment.