Skip to content

Offering: Desending sort_by #45

@jdhedden

Description

@jdhedden

sort_by currently only supports ascending sorts. The following allows descending sorts:

For README.md:

### Usage of `sort_by`

The `sort_by` command also takes a [function argument](#available-function-arguments).
It calls the function on each *line of input*, and uses the results to sort
the *original input* in __ascending__ order.  The `--descending` / `-d` option
will sort the results in __descending__ order.  (There is a `--ascending` / `-a`
option for completeness.)

For ft/ft/commands.sort_by.py:

diff --git a/ft/ft/commands/sort_by.py b/ft/ft/commands/sort_by.py
index b0d0e99..d5e63c0 100644
--- a/ft/ft/commands/sort_by.py
+++ b/ft/ft/commands/sort_by.py
@@ -6,6 +6,19 @@ class SortBy(Command):
     def __init__(self):
         super().__init__("sort_by")
         self.arr = []
+        self.reverse = False
+
+    def add_command_arguments(self, parser):
+        parser.add_argument("--ascending", "-a", dest="reverse",
+                action="store_false", default=False, 
+                help="sort in ascending order (default)")
+        parser.add_argument("--descending", "-d", dest="reverse",
+                action="store_true",
+                help="sort in descending order")
+        return parser
+
+    def parse_additional_command_arguments(self, args):
+        self.reverse = args.reverse
 
     def handle_input(self, value):
         if value.fttype == T_ARRAY and self.column is not None:
@@ -16,5 +29,5 @@ class SortBy(Command):
         self.arr.append((value, result))
 
     def finalize(self):
-        arr = sorted(self.arr, key=lambda x: x[1])
+        arr = sorted(self.arr, key=lambda x: x[1], reverse=self.reverse)
         list(map(lambda x: self.print_formatted(x[0]), arr))

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions