Skip to content

Commit

Permalink
Update Cycle operation.
Browse files Browse the repository at this point in the history
  • Loading branch information
drupol committed Dec 28, 2019
1 parent e999465 commit 940beb4
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 18 deletions.
7 changes: 3 additions & 4 deletions spec/drupol/collection/CollectionSpec.php
Original file line number Diff line number Diff line change
Expand Up @@ -323,16 +323,15 @@ public function it_can_cycle(): void
->beConstructedThrough('with', [['1', '2', '3']]);

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

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

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

Expand Down
4 changes: 2 additions & 2 deletions src/Collection.php
Original file line number Diff line number Diff line change
Expand Up @@ -137,9 +137,9 @@ public function count(): int
*
* @return \drupol\collection\Contract\Collection
*/
public function cycle(int $count = 0): BaseInterface
public function cycle(int $length = 0): BaseInterface
{
return $this->run(new Cycle($count));
return $this->run(new Cycle($length));
}

/**
Expand Down
4 changes: 2 additions & 2 deletions src/Contract/Cycleable.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@
interface Cycleable
{
/**
* @param int $count
* @param int $length
*
* @return \drupol\collection\Contract\Collection<mixed>
*/
public function cycle(int $count = 0): Base;
public function cycle(int $length = 0): Base;
}
29 changes: 19 additions & 10 deletions src/Operation/Cycle.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,10 @@

use Closure;
use drupol\collection\Contract\Operation;
use drupol\collection\Iterator\IterableIterator;
use Generator;
use InfiniteIterator;
use LimitIterator;

/**
* Class Cycle.
Expand All @@ -16,30 +19,36 @@ final class Cycle implements Operation
/**
* @var int
*/
private $count;
private $length;

/**
* Cycle constructor.
*
* @param int $count
* @param int $length
*/
public function __construct(int $count = 0)
public function __construct(int $length = 0)
{
$this->count = $count;
$this->length = $length;
}

/**
* {@inheritdoc}
*/
public function on(iterable $collection): Closure
{
$count = $this->count;
$length = $this->length;

return static function () use ($collection, $count): Generator {
for ($j = 0 === $count ? 1 : 0; $j !== $count; ++$j) {
foreach ($collection as $value) {
yield $value;
}
return static function () use ($collection, $length): Generator {
$cycleIterator = new LimitIterator(
new InfiniteIterator(
new IterableIterator($collection)
),
0,
$length
);

foreach ($cycleIterator as $value) {
yield $value;
}
};
}
Expand Down

0 comments on commit 940beb4

Please sign in to comment.