Skip to content

Commit

Permalink
fix: Update ScanLeft so it doesn't go further if the iterator is not …
Browse files Browse the repository at this point in the history
…valid.
  • Loading branch information
drupol committed Dec 8, 2020
1 parent e518492 commit 5d9e448
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 13 deletions.
8 changes: 4 additions & 4 deletions spec/loophp/collection/CollectionSpec.php
Original file line number Diff line number Diff line change
Expand Up @@ -154,10 +154,10 @@ public function it_can_associate(): void

$this::fromIterable($input)
->associate(
static function ($carry, $key, $value) {
static function (int $carry, int $key, int $value): int {
return $key * 2;
},
static function ($carry, $key, $value) {
static function (int $carry, int $key, int $value): int {
return $value * 2;
}
)
Expand Down Expand Up @@ -726,7 +726,7 @@ public function it_can_every(): void

$this::empty()
->every($callback)
->shouldIterateAs([0 => true]);
->shouldIterateAs([]);

$this::fromIterable(range(0, 10))
->every(
Expand Down Expand Up @@ -1965,7 +1965,7 @@ public function it_can_scanleft(): void

$this::fromIterable([])
->scanLeft($callback, 3)
->shouldIterateAs([3]);
->shouldIterateAs([]);
}

public function it_can_scanleft1(): void
Expand Down
28 changes: 19 additions & 9 deletions src/Operation/ScanLeft.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,15 +35,25 @@ public function __invoke(): Closure
*
* @psalm-return Closure(Iterator<TKey, T>): Generator<int|TKey, T|null>
*/
static function ($initial = null) use ($callback): Closure {
/** @psalm-var Closure(Iterator<TKey, T>):(Generator<int|TKey, T|null>) $pipe */
$pipe = Pipe::of()(
Reduction::of()($callback)($initial),
Prepend::of()($initial)
);
static fn ($initial = null): Closure =>
/**
* @psalm-param Iterator<TKey, T> $iterator
*
* @psalm-return Generator<int|TKey, T|null>
*/
static function (Iterator $iterator) use ($callback, $initial): Generator {
// @todo: See if we cannot find a better way to do this.
if (false === $iterator->valid()) {
return;
}

// Point free style.
return $pipe;
};
/** @psalm-var Closure(Iterator<TKey, T>):(Generator<int|TKey, T|null>) $pipe */
$pipe = Pipe::of()(
Reduction::of()($callback)($initial),
Prepend::of()($initial)
);

return yield from $pipe($iterator);
};
}
}

0 comments on commit 5d9e448

Please sign in to comment.