diff --git a/rxsci/data/sort.py b/rxsci/data/sort.py index 36c7379..a5033a9 100644 --- a/rxsci/data/sort.py +++ b/rxsci/data/sort.py @@ -4,19 +4,22 @@ import rxsci as rs -def sort(key=lambda i: i): +def sort(key=lambda i: i, reverse=False): '''sort items according to key - Items are sorted in ascending order. + Items are sorted in ascending order by default. When reverse is set to + True, they are sorted by descending order. Impementation note: This operator caches all the items of the source - observable before sorting them. It can be used ONLY on BATCH source, and - consumes a lot of memory. + observable before sorting them. Si, it can be used only on a batch source, + and can lead to high memory usage. The source must be an Observable. Args: key: [Optional] function used to extract the sorting key on each item. + reverse: [Optional] Set to True for descendig sorting. + Returns: An observable emitting the sorted items of the source observable. @@ -24,7 +27,7 @@ def sort(key=lambda i: i): def _sort(source): return source.pipe( rs.data.to_list(), - rs.ops.map(lambda i: sorted(i, key=key)), + rs.ops.map(lambda i: sorted(i, key=key, reverse=reverse)), rs.data.to_deque(extend=True), ) diff --git a/rxsci/operators/pandas.py b/rxsci/operators/pandas.py index a21f900..a2020ee 100644 --- a/rxsci/operators/pandas.py +++ b/rxsci/operators/pandas.py @@ -49,7 +49,7 @@ def to_pandas(columns=None): The source must be an Observable. Args: - columns: [Optional] + columns: [Optional] The name of the columns of the dataframe Returns: An observable the emits a single item. This item is a pandas diff --git a/tests/data/test_sort.py b/tests/data/test_sort.py index d0a3b5a..53a6a78 100644 --- a/tests/data/test_sort.py +++ b/tests/data/test_sort.py @@ -15,6 +15,18 @@ def test_sort(): assert actual_result == expected_result +def test_sort_reverse(): + source = [2, 3, 10, 4, 1, 5, 6, 7, 5, 9, 8, 9, 11, 11] + expected_result = [11, 11, 10, 9, 9, 8, 7, 6, 5, 5, 4, 3, 2, 1] + actual_result = [] + + rx.from_(source).pipe( + rs.data.sort(reverse=True) + ).subscribe(on_next=actual_result.append) + + assert actual_result == expected_result + + def test_sort_key(): source = [2, 3, 10, 4, 1, 5, 6, 7, 5, 9, 8, 9, 11, 11] expected_result = [11, 11, 10, 9, 9, 8, 7, 6, 5, 5, 4, 3, 2, 1]