Skip to content

Commit

Permalink
refactor: Update Init operation in point free style. (#186)
Browse files Browse the repository at this point in the history
* refactor: Update `Init` operation in point free style.

* fix: Add missing parameter type in `TakeWhille` operation.

* Use CachingIterator::hasNext().
  • Loading branch information
drupol authored Aug 24, 2021
1 parent 59e20da commit 31b27cc
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 11 deletions.
3 changes: 3 additions & 0 deletions src/Contract/Operation/TakeWhileable.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

namespace loophp\collection\Contract\Operation;

use Iterator;
use loophp\collection\Contract\Collection;

/**
Expand All @@ -23,6 +24,8 @@ interface TakeWhileable
*
* @see https://loophp-collection.readthedocs.io/en/stable/pages/api.html#takewhile
*
* @param callable(T, TKey, Iterator<TKey, T>): bool ...$callbacks
*
* @return Collection<TKey, T>
*/
public function takeWhile(callable ...$callbacks): Collection;
Expand Down
31 changes: 20 additions & 11 deletions src/Operation/Init.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@
*
* @template TKey
* @template T
*
* phpcs:disable Generic.Files.LineLength.TooLong
*/
final class Init extends AbstractOperation
{
Expand All @@ -29,22 +31,29 @@ final class Init extends AbstractOperation
*/
public function __invoke(): Closure
{
return
$callback =
/**
* @param T $value
* @param TKey $key
* @param CachingIterator<TKey, T> $iterator
*/
static fn ($value, $key, CachingIterator $iterator): bool => $iterator->hasNext();

$buildCachingIterator =
/**
* @param Iterator<TKey, T> $iterator
*
* @return Generator<TKey, T>
* @return CachingIterator<TKey, T>
*/
static function (Iterator $iterator): Generator {
$cacheIterator = new CachingIterator($iterator, CachingIterator::FULL_CACHE);
static fn (Iterator $iterator): CachingIterator => new CachingIterator($iterator, CachingIterator::FULL_CACHE);

foreach ($cacheIterator as $key => $current) {
if (false === $iterator->valid()) {
break;
}
/** @var Closure(Iterator<TKey, T>): Generator<TKey, T> $takeWhile */
$takeWhile = Pipe::of()(
$buildCachingIterator,
TakeWhile::of()($callback)
);

yield $key => $current;
}
};
// Point free style.
return $takeWhile;
}
}

0 comments on commit 31b27cc

Please sign in to comment.