Skip to content

Commit d36e7b6

Browse files
authored
Merge pull request #265 from boesing/feature/orderedlist-shuffle
Introduce `OrderedListInterface#shuffle`
2 parents 0692d40 + 3dc21bd commit d36e7b6

File tree

3 files changed

+41
-0
lines changed

3 files changed

+41
-0
lines changed

src/OrderedList.php

+20
Original file line numberDiff line numberDiff line change
@@ -20,10 +20,12 @@
2020
use function array_unshift;
2121
use function array_values;
2222
use function assert;
23+
use function count;
2324
use function hash;
2425
use function implode;
2526
use function is_callable;
2627
use function serialize;
28+
use function shuffle;
2729
use function sort;
2830
use function sprintf;
2931
use function usort;
@@ -471,4 +473,22 @@ public function removeAt(int $index): OrderedListInterface
471473
{
472474
return $this->filter(fn ($_, int $i) => $i !== $index);
473475
}
476+
477+
public function shuffle(): OrderedListInterface
478+
{
479+
if (count($this->data) <= 1) {
480+
return $this;
481+
}
482+
483+
$data = $this->data;
484+
485+
do {
486+
shuffle($data);
487+
} while ($this->data === $data);
488+
489+
$instance = clone $this;
490+
$instance->data = $data;
491+
492+
return $instance;
493+
}
474494
}

src/OrderedListInterface.php

+7
Original file line numberDiff line numberDiff line change
@@ -264,4 +264,11 @@ public function prepend($value): self;
264264
* @return OrderedListInterface<TValue>
265265
*/
266266
public function removeAt(int $index): self;
267+
268+
/**
269+
* Shuffles all the values within the list.
270+
*
271+
* @return OrderedListInterface<TValue>
272+
*/
273+
public function shuffle(): self;
267274
}

tests/GenericOrderedListTest.php

+14
Original file line numberDiff line numberDiff line change
@@ -1473,4 +1473,18 @@ public function testWillRemoveItemAtSpecificPosition(): void
14731473
$list = $list->removeAt(1);
14741474
self::assertSame([1, 3], $list->toNativeArray());
14751475
}
1476+
1477+
public function testWillShuffleValuesInList(): void
1478+
{
1479+
$list = new GenericOrderedList([
1480+
1,
1481+
2,
1482+
3,
1483+
]);
1484+
1485+
$list2 = $list->shuffle();
1486+
self::assertSame([1, 2, 3], $list->toNativeArray());
1487+
self::assertNotSame($list, $list2);
1488+
self::assertNotSame([1, 2, 3], $list2->toNativeArray());
1489+
}
14761490
}

0 commit comments

Comments
 (0)