Skip to content

Commit

Permalink
Use LimitIterator.
Browse files Browse the repository at this point in the history
  • Loading branch information
drupol committed Dec 28, 2019
1 parent 2aee709 commit e999465
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 12 deletions.
4 changes: 3 additions & 1 deletion spec/drupol/collection/CollectionSpec.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
use drupol\collection\Contract\Operation;
use Exception;
use Iterator;
use OutOfRangeException;
use PhpSpec\ObjectBehavior;
use stdClass;

Expand Down Expand Up @@ -1085,7 +1086,8 @@ public function it_can_tail(): void

$this
->tail(-5)
->shouldIterateAs([]);
->shouldThrow(OutOfRangeException::class)
->during('all');

$this
->tail(100)
Expand Down
24 changes: 13 additions & 11 deletions src/Operation/Limit.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@

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

/**
* Class Limit.
Expand All @@ -18,14 +20,21 @@ final class Limit implements Operation
*/
private $limit;

/**
* @var int
*/
private $offset;

/**
* Limit constructor.
*
* @param int $limit
* @param int $offset
*/
public function __construct(int $limit)
public function __construct(int $limit, int $offset = 0)
{
$this->limit = $limit;
$this->offset = $offset;
}

/**
Expand All @@ -34,17 +43,10 @@ public function __construct(int $limit)
public function on(iterable $collection): Closure
{
$limit = $this->limit;
$offset = $this->offset;

return static function () use ($limit, $collection): Generator {
$i = 0;

foreach ($collection as $key => $value) {
yield $key => $value;

if (++$i === $limit) {
break;
}
}
return static function () use ($collection, $offset, $limit): Generator {
yield from new LimitIterator(new IterableIterator($collection), $offset, $limit);
};
}
}

0 comments on commit e999465

Please sign in to comment.