Skip to content

Commit

Permalink
Update Cycle operation.
Browse files Browse the repository at this point in the history
  • Loading branch information
drupol committed Jul 6, 2020
1 parent 20e3573 commit d91a49a
Show file tree
Hide file tree
Showing 4 changed files with 17 additions and 15 deletions.
13 changes: 7 additions & 6 deletions spec/loophp/collection/CollectionSpec.php
Original file line number Diff line number Diff line change
Expand Up @@ -409,20 +409,21 @@ public function it_can_count_its_items(): void

public function it_can_cycle(): void
{
$this
->beConstructedThrough('with', [['1', '2', '3']]);

$this
$this::with(['1', '2', '3'])
->cycle(3)
->shouldIterateAs(['1', '2', '3']);

$this
$this::with(['1', '2', '3'])
->cycle(6)
->shouldIterateAs(['1', '2', '3', '1', '2', '3']);

$this
$this::with(['1', '2', '3'])
->cycle(7)
->shouldIterateAs(['1', '2', '3', '1', '2', '3', '1']);

$this::with(['1', '2', '3'])
->cycle()
->shouldIterateAs([]);
}

public function it_can_distinct(): void
Expand Down
2 changes: 1 addition & 1 deletion src/Collection.php
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ public function count(): int
return $this->transform(new Count());
}

public function cycle(int $length = 0): BaseInterface
public function cycle(?int $length = null): BaseInterface
{
return $this->run(new Cycle($length));
}
Expand Down
5 changes: 1 addition & 4 deletions src/Contract/Operation/Cycleable.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,5 @@

interface Cycleable
{
/**
* @return \loophp\collection\Base|\loophp\collection\Contract\Collection
*/
public function cycle(int $length = 0): Base;
public function cycle(?int $length = null): Base;
}
12 changes: 8 additions & 4 deletions src/Operation/Cycle.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,18 @@

final class Cycle extends AbstractOperation implements Operation
{
public function __construct(int $length = 0)
public function __construct(?int $length = null)
{
$this->storage['length'] = $length;
$this->storage['length'] = $length ?? 0;
}

public function __invoke(): Closure
{
return static function (iterable $collection, int $length): Generator {
if (0 === $length) {
return yield from [];
}

$iterator = new LimitIterator(
new InfiniteIterator(
new IterableIterator($collection)
Expand All @@ -29,8 +33,8 @@ public function __invoke(): Closure
$length
);

foreach ($iterator as $value) {
yield $value;
foreach ($iterator as $key => $value) {
yield $key => $value;
}
};
}
Expand Down

0 comments on commit d91a49a

Please sign in to comment.