Skip to content

Commit

Permalink
sort: add reverse argument
Browse files Browse the repository at this point in the history
  • Loading branch information
MainRo committed Oct 12, 2023
1 parent 2cd3b77 commit f348235
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 6 deletions.
13 changes: 8 additions & 5 deletions rxsci/data/sort.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,27 +4,30 @@
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.
'''
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),
)

Expand Down
2 changes: 1 addition & 1 deletion rxsci/operators/pandas.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
12 changes: 12 additions & 0 deletions tests/data/test_sort.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down

0 comments on commit f348235

Please sign in to comment.