summaryrefslogtreecommitdiff
path: root/it.class
diff options
context:
space:
mode:
authorUrban Müller2020-05-25 17:59:31 +0200
committerUrban Müller2020-05-25 17:59:31 +0200
commit8bf25e3d0df107d9e2920740fccf247903cb612e (patch)
tree27d91d9319d4ed5066231af28596e1f56583a5de /it.class
parent241d2cd913cbda98764161e1c9d23c35156d836d (diff)
downloaditools-8bf25e3d0df107d9e2920740fccf247903cb612e.tar.gz
itools-8bf25e3d0df107d9e2920740fccf247903cb612e.tar.bz2
itools-8bf25e3d0df107d9e2920740fccf247903cb612e.zip
allow sorting and mapping functions in sort()
Diffstat (limited to 'it.class')
-rw-r--r--it.class18
1 files 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;
}