From 8bf25e3d0df107d9e2920740fccf247903cb612e Mon Sep 17 00:00:00 2001
From: Urban Müller
Date: Mon, 25 May 2020 17:59:31 +0200
Subject: allow sorting and mapping functions in sort()

---
 it.class | 18 ++++++++++++++----
 1 file changed, 14 insertions(+), 4 deletions(-)

diff --git a/it.class b/it.class
index 8f7435c..df6c0c0 100644
--- a/it.class
+++ b/it.class
@@ -1182,12 +1182,22 @@ static function json_decode($json, $p = [])
 }
 
 /**
- * Retuns sorted array. mode string can contain combinations of a for assoc, k for key, r for reverse and n for numeric
+ * Retuns sorted array.
+ * @param $mode contains combinations of a for assoc, k for key, r for reverse and n for numeric
+ * @param $compare two arg compare function or single arg map function. $mode can k a "" or omitted
  */
-static function sort($array, $mode = "")
+static function sort($array, $mode = "", $compare = null)
 {
-	$func = it::replace(array('n' => ""), count_chars($mode, 3)) . "sort"; # count_chars sorts flags
-	$func($array, it::match('n', $mode) ? SORT_NUMERIC : 0);
+	if (is_callable($mode) && !(is_string($mode) && strlen($mode) < 3)) # "a" is a func and a mode
+		list($mode, $compare) = [ "", $mode ];
+
+	if (!($arg = $compare))
+		$arg = it::match('n', $mode) ? SORT_NUMERIC : 0;
+	else if (($prefix = "u") && (new ReflectionFunction($compare))->getNumberOfRequiredParameters() == 1)
+		$arg = function($a, $b) use ($compare) { return $compare($a) <=> $compare($b); };
+
+	$func = $prefix . it::replace(array('n' => ""), count_chars($mode, 3)) . "sort"; # count_chars sorts flags
+	$func($array, $arg);
 
 	return $array;
 }
-- 
cgit v1.2.3