Skip to content

Commit

Permalink
Update Last transformation.
Browse files Browse the repository at this point in the history
  • Loading branch information
drupol committed Aug 21, 2020
1 parent f81494a commit 6496559
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 8 deletions.
6 changes: 6 additions & 0 deletions spec/loophp/collection/CollectionSpec.php
Original file line number Diff line number Diff line change
Expand Up @@ -878,6 +878,12 @@ public function it_can_get_the_last_item(): void
$this::fromIterable([])
->last()
->shouldReturn(null);

$this::fromIterable(range('A', 'F'))
->last(static function ($value, $key) {
return false;
}, 'foo')
->shouldReturn('foo');
}

public function it_can_group()
Expand Down
26 changes: 18 additions & 8 deletions src/Transformation/Last.php
Original file line number Diff line number Diff line change
Expand Up @@ -63,17 +63,27 @@ static function ($key, $value): bool {
public function __invoke(Iterator $collection)
{
$callback = $this->callback;
$default = $this->default;
$return = $nothing = new StdClass();
$nothing = new StdClass();

foreach ($collection as $key => $value) {
if (true === $callback($value, $key)) {
$return = $value;
}
}
$callback =
/**
* @param mixed|stdClass $carry
* @param mixed $value
* @param mixed $key
* @psalm-param stdClass|T $carry
* @psalm-param T $value
* @psalm-param TKey $key
*/
static function ($carry, $value, $key) use ($callback) {
return true === $callback($value, $key) ?
$value :
$carry;
};

$return = (new Transform(new FoldLeft($callback, $nothing)))($collection);

return ($return !== $nothing) ?
$return :
$default;
$this->default;
}
}

0 comments on commit 6496559

Please sign in to comment.