Skip to content

Commit

Permalink
Create a static "times" method on the collection (#18457)
Browse files Browse the repository at this point in the history
  • Loading branch information
JosephSilber authored and taylorotwell committed Mar 25, 2017
1 parent 6ed63eb commit 5e86420
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/Illuminate/Support/Collection.php
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,22 @@ public static function make($items = [])
return new static($items);
}

/**
* Create a new collection by invoking the callback a given amount of times.
*
* @param int $amount
* @param callable $callback
* @return static
*/
public static function times($amount, callable $callback)
{
if ($amount < 1) {
return new static;
}

return (new static(range(1, $amount)))->map($callback);
}

/**
* Get all of the items in the collection.
*
Expand Down
19 changes: 19 additions & 0 deletions tests/Support/SupportCollectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -936,6 +936,25 @@ public function testMakeMethodFromArray()
$this->assertEquals(['foo' => 'bar'], $collection->all());
}

public function testTimesMethod()
{
$two = Collection::times(2, function ($number) {
return 'slug-'.$number;
});

$zero = Collection::times(0, function ($number) {
return 'slug-'.$number;
});

$negative = Collection::times(-4, function ($number) {
return 'slug-'.$number;
});

$this->assertEquals(['slug-1', 'slug-2'], $two->all());
$this->assertTrue($zero->isEmpty());
$this->assertTrue($negative->isEmpty());
}

public function testConstructMakeFromObject()
{
$object = new stdClass();
Expand Down

0 comments on commit 5e86420

Please sign in to comment.