Skip to content

Commit

Permalink
Update Filter operation using \CallbackFilterIterator.
Browse files Browse the repository at this point in the history
  • Loading branch information
drupol committed Dec 29, 2019
1 parent 940beb4 commit 96decd5
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 14 deletions.
6 changes: 3 additions & 3 deletions spec/drupol/collection/CollectionSpec.php
Original file line number Diff line number Diff line change
Expand Up @@ -408,8 +408,8 @@ public function it_can_filter_its_element(): void
$this
->beConstructedThrough('with', [$input]);

$callable = static function ($item) {
return $item % 2;
$callable = static function ($value, $key, $iterator) {
return $value % 2;
};

$this
Expand All @@ -425,7 +425,7 @@ public function it_can_filter_its_element(): void
$this
->filter()
->normalize()
->shouldIterateAs([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
->shouldIterateAs([]);
}

public function it_can_flatten(): void
Expand Down
16 changes: 5 additions & 11 deletions src/Operation/Filter.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@

namespace drupol\collection\Operation;

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

/**
Expand Down Expand Up @@ -35,19 +37,11 @@ public function on(iterable $collection): Closure
{
$callbacks = $this->callbacks;

if ([] === $callbacks) {
$callbacks[] = static function ($value) {
return $value;
};
}

return static function () use ($callbacks, $collection): Generator {
$iterator = $collection;

foreach ($callbacks as $callback) {
foreach ($collection as $key => $value) {
if (true === (bool) $callback($value, $key)) {
yield $key => $value;
}
}
yield from $iterator = new CallbackFilterIterator(new IterableIterator($iterator), $callback);
}
};
}
Expand Down

0 comments on commit 96decd5

Please sign in to comment.