Skip to content

Commit 2f03d11

Browse files
committed
Create a static range method on the collection
1 parent b2b1f99 commit 2f03d11

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

src/Illuminate/Support/Collection.php

+16
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,22 @@ public static function make($items = [])
5858
return new static($items);
5959
}
6060

61+
/**
62+
* Create a new collection by invoking the callback a given amount of times.
63+
*
64+
* @param int $amount
65+
* @param callable $callback
66+
* @return static
67+
*/
68+
public static function times($amount, callable $callback)
69+
{
70+
if ($amount < 1) {
71+
return new static;
72+
}
73+
74+
return (new static(range(1, $amount)))->map($callback);
75+
}
76+
6177
/**
6278
* Get all of the items in the collection.
6379
*

tests/Support/SupportCollectionTest.php

+19
Original file line numberDiff line numberDiff line change
@@ -936,6 +936,25 @@ public function testMakeMethodFromArray()
936936
$this->assertEquals(['foo' => 'bar'], $collection->all());
937937
}
938938

939+
public function testTimesMethod()
940+
{
941+
$two = Collection::times(2, function ($number) {
942+
return 'slug-'.$number;
943+
});
944+
945+
$zero = Collection::times(0, function ($number) {
946+
return 'slug-'.$number;
947+
});
948+
949+
$negative = Collection::times(-4, function ($number) {
950+
return 'slug-'.$number;
951+
});
952+
953+
$this->assertEquals(['slug-1', 'slug-2'], $two->all());
954+
$this->assertTrue($zero->isEmpty());
955+
$this->assertTrue($negative->isEmpty());
956+
}
957+
939958
public function testConstructMakeFromObject()
940959
{
941960
$object = new stdClass();

0 commit comments

Comments
 (0)