Skip to content

Commit

Permalink
refactor: Improve Has operation.
Browse files Browse the repository at this point in the history
  • Loading branch information
drupol committed Apr 20, 2021
1 parent 583e95b commit 1425343
Showing 1 changed file with 17 additions and 35 deletions.
52 changes: 17 additions & 35 deletions src/Operation/Has.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

namespace loophp\collection\Operation;

use ArrayIterator;
use Closure;
use Generator;
use Iterator;
Expand All @@ -30,43 +29,26 @@ public function __invoke(): Closure
* @psalm-return Closure(Iterator<TKey, T>): Generator<int|TKey, bool>
*/
static function (callable ...$callbacks): Closure {
return
/**
* @psalm-param Iterator<TKey, T> $iterator
*
* @psalm-return Generator<int|TKey, bool>
*/
static function (Iterator $iterator) use ($callbacks): Generator {
/** @psalm-var list<Closure(T, TKey, Iterator<TKey, T>): bool> $callbacks */
$callbacks = array_map(
/** @psalm-var Closure(Iterator<TKey, T>): Generator<int|TKey, bool> $pipe */
$pipe = MatchOne::of()(static fn (): bool => true)(
...array_map(
static fn (callable $callback): callable =>
/**
* @psalm-param callable(T, TKey, Iterator<TKey, T>): bool $callback
* @param mixed $value
* @psalm-param T $value
*
* @param mixed $key
* @psalm-param TKey $key
*
* @psalm-param Iterator<TKey, T> $iterator
*/
static fn (callable $callback): Closure =>
/**
* @param mixed $value
* @psalm-param T $value
*
* @param mixed $key
* @psalm-param TKey $key
*
* @psalm-param Iterator<TKey, T> $iterator
*/
static fn ($value, $key, Iterator $iterator): bool => $callback($value, $key, $iterator) === $value,
$callbacks
);
static fn ($value, $key, Iterator $iterator): bool => $callback($value, $key, $iterator) === $value,
$callbacks
)
);

foreach ($iterator as $key => $current) {
/** @psalm-var Iterator<int, bool> $result */
$result = MatchOne::of()(static fn (): bool => true)(...$callbacks)(Pair::of()(new ArrayIterator([$key, $current])));

if (true === $result->current()) {
return yield $key => true;
}
}

return yield false;
};
// Point free style.
return $pipe;
};
}
}

0 comments on commit 1425343

Please sign in to comment.