From b31581dc804d3fd3e1e6014cf5e9b54177549216 Mon Sep 17 00:00:00 2001 From: Jakob Ketterl Date: Wed, 14 Dec 2022 01:22:48 +0100 Subject: [PATCH] implement active list transformation --- owrx/active/list/__init__.py | 20 ++++++++++++++++++++ test/owrx/active/list/test_active_list.py | 23 +++++++++++++++++++++++ 2 files changed, 43 insertions(+) diff --git a/owrx/active/list/__init__.py b/owrx/active/list/__init__.py index 9c859f8..a088f0f 100644 --- a/owrx/active/list/__init__.py +++ b/owrx/active/list/__init__.py @@ -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 diff --git a/test/owrx/active/list/test_active_list.py b/test/owrx/active/list/test_active_list.py index 9b83438..1b658a1 100644 --- a/test/owrx/active/list/test_active_list.py +++ b/test/owrx/active/list/test_active_list.py @@ -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")