Skip to content

Commit

Permalink
Update chunk operation.
Browse files Browse the repository at this point in the history
  • Loading branch information
drupol committed Dec 25, 2019
1 parent b7853d9 commit cba479e
Showing 1 changed file with 11 additions and 15 deletions.
26 changes: 11 additions & 15 deletions src/Operation/Chunk.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,12 @@

namespace drupol\collection\Operation;

use ArrayIterator;
use Closure;
use drupol\collection\Contract\Operation;
use drupol\collection\Iterator\ClosureIterator;
use Generator;

use function count;

/**
* Class Chunk.
*/
Expand Down Expand Up @@ -44,23 +44,19 @@ public function on(iterable $collection): Closure
}

return static function () use ($length, $collection): Generator {
$iterator = new ClosureIterator(
static function () use ($collection): Generator {
foreach ($collection as $key => $value) {
yield $value;
}
}
);
$values = [];

while ($iterator->valid()) {
$values = [];
foreach ($collection as $key => $value) {
if (count($values) === $length) {
yield $values;

for ($i = 0; $iterator->valid() && $i < $length; $i++, $iterator->next()) {
$values[] = $iterator->current();
$values = [$value];
} else {
$values[] = $value;
}

yield new ArrayIterator($values);
}

yield $values;
};
}
}

0 comments on commit cba479e

Please sign in to comment.