Skip to content

Commit

Permalink
refactor: Update Distinct operation.
Browse files Browse the repository at this point in the history
Get rid of referenced parameter $seen.

Signed-off-by: Pol Dellaiera <pol.dellaiera@protonmail.com>
  • Loading branch information
drupol committed Jan 3, 2021
1 parent c7aebfe commit 80e676b
Showing 1 changed file with 25 additions and 14 deletions.
39 changes: 25 additions & 14 deletions src/Operation/Distinct.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,27 +22,38 @@ final class Distinct extends AbstractOperation
*/
public function __invoke(): Closure
{
/** @psalm-var list<T> $seen */
$seen = [];

$filterCallback =
$foldLeftCallback =
/**
* @param mixed $value
* @psalm-param T $value
* @psalm-param array<int, list<array{0:TKey, 1:T}>> $seen
* @psalm-param array{0:TKey, 1:T} $value
*
* @psalm-return array<int, list<array{0:TKey, 1:T}>>
*/
static function ($value) use (&$seen): bool {
$return = in_array($value, $seen, true);
static function (array $seen, array $value): array {
$return = false;

foreach ($seen as $seenTuple) {
if ($seenTuple[1] === $value[1]) {
$return = true;
break;
}
}

/** @psalm-var list<T> $seen */
$seen[] = $value;
if (false === $return) {
$seen[] = $value;
}

return !$return;
return $seen;
};

/** @psalm-var Closure(Iterator<TKey, T>): Generator<TKey, T> $filter */
$filter = Filter::of()($filterCallback);
$pipe = Pipe::of()(
Pack::of(),
FoldLeft::of()($foldLeftCallback)([]),
Unwrap::of(),
Unpack::of(),
);

// Point free style.
return $filter;
return $pipe;
}
}

0 comments on commit 80e676b

Please sign in to comment.