Skip to content

Commit d52ef24

Browse files
authored
Collection->random() add preserve keys option (#43267)
1 parent 10d8cef commit d52ef24

File tree

2 files changed

+14
-3
lines changed

2 files changed

+14
-3
lines changed

src/Illuminate/Collections/Collection.php

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -979,21 +979,22 @@ public function put($key, $value)
979979
* Get one or a specified number of items randomly from the collection.
980980
*
981981
* @param (callable(TValue): int)|int|null $number
982+
* @param bool $preserveKeys
982983
* @return static<int, TValue>|TValue
983984
*
984985
* @throws \InvalidArgumentException
985986
*/
986-
public function random($number = null)
987+
public function random($number = null, $preserveKeys = false)
987988
{
988989
if (is_null($number)) {
989990
return Arr::random($this->items);
990991
}
991992

992993
if (is_callable($number)) {
993-
return new static(Arr::random($this->items, $number($this)));
994+
return new static(Arr::random($this->items, $number($this), $preserveKeys));
994995
}
995996

996-
return new static(Arr::random($this->items, $number));
997+
return new static(Arr::random($this->items, $number, $preserveKeys));
997998
}
998999

9991000
/**

tests/Support/SupportCollectionTest.php

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2286,9 +2286,19 @@ public function testRandom($collection)
22862286
$this->assertInstanceOf($collection, $random);
22872287
$this->assertCount(2, $random);
22882288

2289+
$random = $data->random(2, true);
2290+
$this->assertInstanceOf($collection, $random);
2291+
$this->assertCount(2, $random);
2292+
$this->assertCount(2, array_intersect_assoc($random->all(), $data->all()));
2293+
22892294
$random = $data->random(fn ($items) => min(10, count($items)));
22902295
$this->assertInstanceOf($collection, $random);
22912296
$this->assertCount(6, $random);
2297+
2298+
$random = $data->random(fn ($items) => min(10, count($items) - 1), true);
2299+
$this->assertInstanceOf($collection, $random);
2300+
$this->assertCount(5, $random);
2301+
$this->assertCount(5, array_intersect_assoc($random->all(), $data->all()));
22922302
}
22932303

22942304
/**

0 commit comments

Comments
 (0)