sharkdp / shell-functools

Functional programming tools for the shell
MIT License
1.19k stars 49 forks source link

Offering: Desending sort_by #45

Open jdhedden opened 2 years ago

jdhedden commented 2 years ago

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.sortby.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))
sharkdp commented 2 years ago

Great idea. Note that I'm not using this project myself anymore, so I'm not really actively maintaining it. I'd be happy to merge a PR with proper tests though.