diff --git a/src/Support/sortByMany.php b/src/Support/sortByMany.php index 1e437b3..cebade1 100644 --- a/src/Support/sortByMany.php +++ b/src/Support/sortByMany.php @@ -9,7 +9,9 @@ function sortByMany(array $items, array $comparisons): array $comparison = normalize($comparison); $prop = $comparison[0] ?? null; $direction = strtolower((string) ($comparison[1] ?? 'asc')); - $result = dataGet($a, $prop) <=> dataGet($b, $prop); + $result = (! is_string($prop) && is_callable($prop)) + ? $prop($a, $b) + : dataGet($a, $prop) <=> dataGet($b, $prop); if ($result !== 0) { return $direction === 'desc' ? -$result : $result; diff --git a/tests/Arr/SortByFnTest.php b/tests/Arr/SortByFnTest.php new file mode 100644 index 0000000..94d46dd --- /dev/null +++ b/tests/Arr/SortByFnTest.php @@ -0,0 +1,20 @@ + 'Aaron', 'score' => 43], + ['name' => 'Sophie', 'score' => 87], + ['name' => 'Aaron', 'score' => 59], + ['name' => 'Sophie', 'score' => 62], + ] |> sortBy([ + fn (array $a, array $b) => $a['name'] <=> $b['name'], + fn (array $a, array $b) => $b['score'] <=> $a['score'], + ]))->toBe([ + 2 => ['name' => 'Aaron', 'score' => 59], + 0 => ['name' => 'Aaron', 'score' => 43], + 1 => ['name' => 'Sophie', 'score' => 87], + 3 => ['name' => 'Sophie', 'score' => 62], + ]); +});