From 31b27cc6c950981af1ec1a0dc9481808d44dc428 Mon Sep 17 00:00:00 2001 From: Pol Dellaiera Date: Tue, 24 Aug 2021 11:48:45 +0200 Subject: [PATCH] refactor: Update `Init` operation in point free style. (#186) * refactor: Update `Init` operation in point free style. * fix: Add missing parameter type in `TakeWhille` operation. * Use CachingIterator::hasNext(). --- src/Contract/Operation/TakeWhileable.php | 3 +++ src/Operation/Init.php | 31 +++++++++++++++--------- 2 files changed, 23 insertions(+), 11 deletions(-) diff --git a/src/Contract/Operation/TakeWhileable.php b/src/Contract/Operation/TakeWhileable.php index 14f5ec609..7ca19e176 100644 --- a/src/Contract/Operation/TakeWhileable.php +++ b/src/Contract/Operation/TakeWhileable.php @@ -9,6 +9,7 @@ namespace loophp\collection\Contract\Operation; +use Iterator; use loophp\collection\Contract\Collection; /** @@ -23,6 +24,8 @@ interface TakeWhileable * * @see https://loophp-collection.readthedocs.io/en/stable/pages/api.html#takewhile * + * @param callable(T, TKey, Iterator): bool ...$callbacks + * * @return Collection */ public function takeWhile(callable ...$callbacks): Collection; diff --git a/src/Operation/Init.php b/src/Operation/Init.php index 21d4ebc72..bc4c334f6 100644 --- a/src/Operation/Init.php +++ b/src/Operation/Init.php @@ -19,6 +19,8 @@ * * @template TKey * @template T + * + * phpcs:disable Generic.Files.LineLength.TooLong */ final class Init extends AbstractOperation { @@ -29,22 +31,29 @@ final class Init extends AbstractOperation */ public function __invoke(): Closure { - return + $callback = + /** + * @param T $value + * @param TKey $key + * @param CachingIterator $iterator + */ + static fn ($value, $key, CachingIterator $iterator): bool => $iterator->hasNext(); + + $buildCachingIterator = /** * @param Iterator $iterator * - * @return Generator + * @return CachingIterator */ - 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): Generator $takeWhile */ + $takeWhile = Pipe::of()( + $buildCachingIterator, + TakeWhile::of()($callback) + ); - yield $key => $current; - } - }; + // Point free style. + return $takeWhile; } }