diff --git a/spec/loophp/collection/CollectionSpec.php b/spec/loophp/collection/CollectionSpec.php index 4378a9aba..988c91fb7 100644 --- a/spec/loophp/collection/CollectionSpec.php +++ b/spec/loophp/collection/CollectionSpec.php @@ -961,6 +961,19 @@ public function it_can_get_the_last_item(): void $this::fromIterable([]) ->last() ->shouldIterateAs([]); + + $input = [ + ['a'], + ['b', 'a'], + ['c', 'b', 'a'], + ['d', 'c', 'b', 'a'], + ]; + + $this::fromIterable($input) + ->last() + ->shouldIterateAs([ + 3 => ['d', 'c', 'b', 'a'], + ]); } public function it_can_group() diff --git a/src/Operation/Last.php b/src/Operation/Last.php index 45bfb20c2..8d0fa188d 100644 --- a/src/Operation/Last.php +++ b/src/Operation/Last.php @@ -4,6 +4,7 @@ namespace loophp\collection\Operation; +use CachingIterator; use Closure; use Generator; use Iterator; @@ -31,14 +32,17 @@ static function (Iterator $iterator): Generator { return yield from []; } - $key = $iterator->key(); - $current = $iterator->current(); + $cachingIterator = new CachingIterator($iterator, CachingIterator::FULL_CACHE); - for (; $iterator->valid(); $iterator->next()) { - $key = $iterator->key(); - $current = $iterator->current(); + while ($iterator->valid()) { + $cachingIterator->next(); } + /** @psalm-var TKey $key */ + $key = $cachingIterator->key(); + /** @psalm-var T $current */ + $current = $cachingIterator->current(); + return yield $key => $current; }; }