Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat/list utils #36

Merged
merged 1 commit into from
Mar 23, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions ovos_utils/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,18 @@ def rotate_list(l, n=1):
return l[n:] + l[:n]


def flatten_list(some_list, tuples=True):
_flatten = lambda l: [item for sublist in l for item in sublist]
if tuples:
while any(isinstance(x, list) or isinstance(x, tuple)
for x in some_list):
some_list = _flatten(some_list)
else:
while any(isinstance(x, list) for x in some_list):
some_list = _flatten(some_list)
return some_list


def datestr2ts(datestr):
y = int(datestr[:4])
m = int(datestr[4:6])
Expand Down
15 changes: 14 additions & 1 deletion test/unittests/test_utils.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import unittest
from ovos_utils import rotate_list, camel_case_split, get_handler_name

from ovos_utils import rotate_list, camel_case_split, get_handler_name, flatten_list


class TestHelpers(unittest.TestCase):
Expand All @@ -14,10 +15,22 @@ def some_function():
self.assertEqual(camel_case_split("MyAwesomeSkill"),
"My Awesome Skill")

def test_list_utils(self):
self.assertEqual(rotate_list([1, 2, 3]), [2, 3, 1])
self.assertEqual(rotate_list([1, 2, 3], 2), [3, 1, 2])
self.assertEqual(rotate_list([1, 2, 3], 3), [1, 2, 3])

self.assertEqual(rotate_list([1, 2, 3], -1), [3, 1, 2])
self.assertEqual(rotate_list([1, 2, 3], -2), [2, 3, 1])
self.assertEqual(rotate_list([1, 2, 3], -3), [1, 2, 3])

self.assertEqual(
flatten_list([["A", "B"], ["C"]]), ["A", "B", "C"]
)
self.assertEqual(
flatten_list([("A", "B")]), ["A", "B"]
)
self.assertEqual(
flatten_list([("A", "B"), ["C"], [["D", ["E", ["F"]]]]]),
["A", "B", "C", "D", "E", "F"]
)