Skip to content

Commit

Permalink
Simplify the use of the Sort callback in userland.
Browse files Browse the repository at this point in the history
  • Loading branch information
drupol committed Aug 8, 2020
1 parent c61749c commit 5014004
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 13 deletions.
1 change: 1 addition & 0 deletions docs/pages/api.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1069,6 +1069,7 @@ Signature: ``Collection::sort(?callable $callback = null);``
Operation\Sortable::BY_VALUES,
static function ($left, $right): int {
// Do the comparison here.
return $left <=> $right;
}
);
Expand Down
4 changes: 2 additions & 2 deletions spec/loophp/collection/CollectionSpec.php
Original file line number Diff line number Diff line change
Expand Up @@ -1650,8 +1650,8 @@ public function it_can_sort(): void
$this::fromIterable($input)
->sort(
Operation\Sortable::BY_VALUES,
static function (array $left, array $right): int {
return current($right) <=> current($left);
static function ($left, $right): int {
return $right <=> $left;
}
)
->shouldIterateAs(array_combine(range('A', 'E'), range('E', 'A')));
Expand Down
27 changes: 16 additions & 11 deletions src/Operation/Sort.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,6 @@ public function __invoke(): Closure
* @psalm-return \Generator<TKey, T>
*/
static function (Iterator $iterator, int $type, callable $callback): Generator {
$operations = [
'before' => [],
'after' => [],
];

switch ($type) {
case Operation\Sortable::BY_VALUES:
$operations = [
Expand All @@ -62,21 +57,31 @@ static function (Iterator $iterator, int $type, callable $callback): Generator {
throw new Exception('Invalid sort type.');
}

$callback =
/**
* @psalm-param array{TKey, T} $left
* @psalm-param array{TKey, T} $right
*/
static function (array $left, array $right) use ($callback): int {
return $callback(current($left), current($right));
};

$arrayIterator = new ArrayIterator(iterator_to_array((new Run(...$operations['before']))($iterator)));
$arrayIterator->uasort($callback);
$arrayIterator = (new Run(...$operations['after']))($arrayIterator);

return yield from $arrayIterator;
return yield from (new Run(...$operations['after']))($arrayIterator);
};
}

/**
* @psalm-param array{TKey, T} $left
* @psalm-param T $left
* @psalm-param T $right
*
* @psalm-param array{TKey, T} $right
* @param mixed $left
* @param mixed $right
*/
private function compare(array $left, array $right): int
private function compare($left, $right): int
{
return current($left) <=> current($right);
return $left <=> $right;
}
}

0 comments on commit 5014004

Please sign in to comment.