Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[5.6] Add ability to seed Arr::shuffle() #23490

Merged
merged 2 commits into from Mar 12, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
13 changes: 11 additions & 2 deletions src/Illuminate/Support/Arr.php
Expand Up @@ -541,11 +541,20 @@ public static function set(&$array, $key, $value)
* Shuffle the given array and return the result.
*
* @param array $array
* @param int|null $seed
* @return array
*/
public static function shuffle($array)
public static function shuffle($array, $seed = null)
{
shuffle($array);
if (is_null($seed)) {
shuffle($array);
} else {
srand($seed);

usort($array, function () {
return rand(-1, 1);
});
}

return $array;
}
Expand Down
14 changes: 1 addition & 13 deletions src/Illuminate/Support/Collection.php
Expand Up @@ -1360,19 +1360,7 @@ public function shift()
*/
public function shuffle($seed = null)
{
$items = $this->items;

if (is_null($seed)) {
shuffle($items);
} else {
srand($seed);

usort($items, function () {
return rand(-1, 1);
});
}

return new static($items);
return new static(Arr::shuffle($this->items, $seed));
}

/**
Expand Down
8 changes: 8 additions & 0 deletions tests/Support/SupportArrTest.php
Expand Up @@ -498,6 +498,14 @@ public function testSet()
$this->assertEquals(['products' => ['desk' => ['price' => 200]]], $array);
}

public function testShuffleWithSeed()
{
$this->assertEquals(
Arr::shuffle(range(0, 100, 10), 1234),
Arr::shuffle(range(0, 100, 10), 1234)
);
}

public function testSort()
{
$unsorted = [
Expand Down