Skip to content

Commit

Permalink
refactor: Improve Intersperse operation.
Browse files Browse the repository at this point in the history
Avoid using local variables and use iterators.
  • Loading branch information
drupol committed Dec 11, 2021
1 parent c109e6e commit a208d4c
Showing 1 changed file with 14 additions and 3 deletions.
17 changes: 14 additions & 3 deletions src/Operation/Intersperse.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,11 @@

namespace loophp\collection\Operation;

use AppendIterator;
use ArrayIterator;
use Closure;
use Generator;
use InfiniteIterator;
use InvalidArgumentException;
use Iterator;

Expand Down Expand Up @@ -62,15 +65,23 @@ static function (Iterator $iterator) use ($element, $atEvery, $startAt): Generat
);
}

$current = 0;
$intersperse = new AppendIterator();
$intersperse->append(
new ArrayIterator(array_fill(0, $startAt, 1))
);
$intersperse->append(
new InfiniteIterator(new ArrayIterator(range(0, $atEvery - 1)))
);
$intersperse->rewind();

foreach ($iterator as $key => $value) {
if ($startAt === $current++) {
$startAt += $atEvery;
if (0 === $intersperse->current()) {
yield $element;
}

yield $key => $value;

$intersperse->next();
}
};
}
Expand Down

0 comments on commit a208d4c

Please sign in to comment.