Skip to content

Commit

Permalink
refactor: Minor optimization in Collection::fromCallable().
Browse files Browse the repository at this point in the history
  • Loading branch information
drupol committed Jan 26, 2021
1 parent 0f2d096 commit 6d2e65a
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 22 deletions.
41 changes: 31 additions & 10 deletions spec/loophp/collection/CollectionSpec.php
Original file line number Diff line number Diff line change
Expand Up @@ -302,18 +302,39 @@ public function it_can_be_constructed_from_empty(): void

public function it_can_be_constructed_with_a_closure(): void
{
$this
->beConstructedThrough('fromCallable', [
static function (int $a, int $b): Generator {
return yield from range($a, $b);
},
1,
5,
]);
$test = $this::fromCallable(
static function (int $a, int $b): Generator {
return yield from range($a, $b);
},
1,
5,
);

$this->shouldImplement(Collection::class);
$test->shouldImplement(Collection::class);

$this
$test
->getIterator()
->shouldIterateAs(
[
1,
2,
3,
4,
5,
]
);

$test = $this::fromCallable(
static function (int $a, int $b): array {
return range($a, $b);
},
1,
5,
);

$test->shouldImplement(Collection::class);

$test
->getIterator()
->shouldIterateAs(
[
Expand Down
13 changes: 1 addition & 12 deletions src/Collection.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
use Closure;
use Generator;
use Iterator;
use IteratorIterator;
use loophp\collection\Contract\Collection as CollectionInterface;
use loophp\collection\Contract\Operation;
use loophp\collection\Iterator\ClosureIterator;
Expand Down Expand Up @@ -351,17 +350,7 @@ public function frequency(): CollectionInterface

public static function fromCallable(callable $callable, ...$parameters): self
{
return new self(
/**
* @psalm-param callable(T...) $callable
* @psalm-param list<T> $parameters
*
* @psalm-return Iterator<TKey, T>
*/
static fn (callable $callable, array $parameters): Iterator => new IteratorIterator($callable(...$parameters)),
$callable,
$parameters
);
return new self($callable, ...$parameters);
}

public static function fromFile(string $filepath): self
Expand Down

0 comments on commit 6d2e65a

Please sign in to comment.