Skip to content

Commit

Permalink
Update Since operation.
Browse files Browse the repository at this point in the history
  • Loading branch information
drupol committed Jun 27, 2020
1 parent 4da37bc commit c3b420c
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 9 deletions.
4 changes: 2 additions & 2 deletions spec/loophp/collection/CollectionSpec.php
Original file line number Diff line number Diff line change
Expand Up @@ -1249,10 +1249,10 @@ static function ($letter) {
$this
->since(
static function ($letter) {
return 'b' === $letter;
return 'x' === $letter;
},
static function ($letter) {
return 'x' === $letter;
return 1 === mb_strlen($letter);
}
)
->shouldIterateAs([23 => 'x', 24 => 'y', 25 => 'z']);
Expand Down
19 changes: 12 additions & 7 deletions src/Operation/Since.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use Closure;
use Generator;
use loophp\collection\Contract\Operation;
use loophp\collection\Iterator\IterableIterator;

final class Since extends AbstractOperation implements Operation
{
Expand All @@ -21,20 +22,24 @@ public function __construct(callable ...$callbacks)
public function __invoke(): Closure
{
return static function (iterable $collection, array $callbacks): Generator {
foreach ($collection as $key => $value) {
$iterator = new IterableIterator($collection);

while ($iterator->valid()) {
$result = 1;

foreach ($callbacks as $keyCallback => $callback) {
$result &= $callback($value, $key);

if (1 === $result) {
unset($callbacks[$keyCallback]);
}
$result &= $callback($iterator->current(), $iterator->key());
}

if (1 === $result) {
yield $key => $value;
break;
}

$iterator->next();
}

for (; $iterator->valid(); $iterator->next()) {
yield $iterator->key() => $iterator->current();
}
};
}
Expand Down

0 comments on commit c3b420c

Please sign in to comment.