Skip to content

Commit

Permalink
refactor: Optimize Group operation.
Browse files Browse the repository at this point in the history
  • Loading branch information
drupol committed Jan 2, 2021
1 parent 3d4786b commit aa418fe
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 27 deletions.
16 changes: 12 additions & 4 deletions spec/loophp/collection/CollectionSpec.php
Original file line number Diff line number Diff line change
Expand Up @@ -1132,11 +1132,19 @@ public function it_can_group(): void
0 => [0 => 'M'],
1 => [0 => 'i'],
2 => [0 => 's', 1 => 's'],
4 => [0 => 'i'],
5 => [0 => 's', 1 => 's'],
3 => [0 => 'i'],
4 => [0 => 's', 1 => 's'],
5 => [0 => 'i'],
6 => [0 => 'p', 1 => 'p'],
7 => [0 => 'i'],
8 => [0 => 'p', 1 => 'p'],
10 => [0 => 'i'],
]);

$this::fromString('aabbcc')
->group()
->shouldIterateAs([
0 => [0 => 'a', 1 => 'a'],
1 => [0 => 'b', 1 => 'b'],
2 => [0 => 'c', 1 => 'c'],
]);
}

Expand Down
44 changes: 21 additions & 23 deletions src/Operation/Group.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,29 +29,27 @@ public function __invoke(): Closure
* @psalm-return Generator<int, list<T>>
*/
static function (Iterator $iterator): Generator {
$spanCallback =
/**
* @param mixed $current
* @psalm-param T $current
*
* @psalm-return Closure(T): bool
*/
static fn ($current): Closure =>
/**
* @param mixed $value
* @psalm-param T $value
*/
static fn ($value): bool => $value === $current;

do {
/** @psalm-var Iterator<int, Iterator<TKey, T>> $span */
$span = Span::of()($spanCallback($iterator->current()))($iterator);

yield $iterator->key() => [...$span->current()];

$span->next();
$iterator = $span->current();
} while ($iterator->valid());
$last = [];

foreach ($iterator as $current) {
if (current($last) === $current) {
$last[] = $current;

continue;
}

if (current($last) === false) {
$last = [$current];

continue;
}

yield $last;

$last = [$current];
}

yield $last;
};
}
}

0 comments on commit aa418fe

Please sign in to comment.