implement active list transformation

This commit is contained in:
Jakob Ketterl 2022-12-14 01:22:48 +01:00
parent f73c62c5df
commit b31581dc80
2 changed files with 43 additions and 0 deletions

View File

@ -33,6 +33,21 @@ class ActiveListListener(ABC):
pass
class ActiveListTransformationListener(ActiveListListener):
def __init__(self, transformation: callable, target: "ActiveList"):
self.transformation = transformation
self.target = target
def onListChange(self, changes: list[ActiveListChange]):
for change in changes:
if isinstance(change, ActiveListIndexUpdated):
self.target[change.index] = self.transformation(change.newValue)
elif isinstance(change, ActiveListIndexAppended):
self.target.append(self.transformation(change.newValue))
elif isinstance(change, ActiveListIndexDeleted):
del self.target[change.index]
class ActiveList:
def __init__(self, elements: list = None):
self.delegate = elements.copy() if elements is not None else []
@ -62,6 +77,11 @@ class ActiveList:
def remove(self, value):
self.__delitem__(self.delegate.index(value))
def map(self, transform: callable):
res = ActiveList([transform(v) for v in self])
self.addListener(ActiveListTransformationListener(transform, res))
return res
def __setitem__(self, key, value):
if self.delegate[key] == value:
return

View File

@ -98,3 +98,26 @@ class ActiveListTest(TestCase):
list.removeListener(listenerMock)
list[0] = "someothervalue"
listenerMock.onListChange.assert_not_called()
def testListMapTransformation(self):
list = ActiveList(["somevalue"])
transformedList = list.map(lambda x: "prefix-{}".format(x))
self.assertEqual(transformedList[0], "prefix-somevalue")
def testActiveTransformationUpdate(self):
list = ActiveList(["initialvalue"])
transformedList = list.map(lambda x: "prefix-{}".format(x))
list[0] = "testvalue"
self.assertEqual(transformedList[0], "prefix-testvalue")
def testActiveTransformationAppend(self):
list = ActiveList(["initialvalue"])
transformedList = list.map(lambda x: "prefix-{}".format(x))
list.append("newvalue")
self.assertEqual(transformedList[1], "prefix-newvalue")
def testActiveTransformationDelete(self):
list = ActiveList(["value1", "value2"])
transformedList = list.map(lambda x: "prefix-{}".format(x))
del list[0]
self.assertEqual(transformedList[0], "prefix-value2")