Skip to content

Commit

Permalink
Merge pull request #265 from boesing/feature/orderedlist-shuffle
Browse files Browse the repository at this point in the history
Introduce `OrderedListInterface#shuffle`
  • Loading branch information
boesing authored Aug 22, 2024
2 parents 0692d40 + 3dc21bd commit d36e7b6
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 0 deletions.
20 changes: 20 additions & 0 deletions src/OrderedList.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,12 @@
use function array_unshift;
use function array_values;
use function assert;
use function count;
use function hash;
use function implode;
use function is_callable;
use function serialize;
use function shuffle;
use function sort;
use function sprintf;
use function usort;
Expand Down Expand Up @@ -471,4 +473,22 @@ public function removeAt(int $index): OrderedListInterface
{
return $this->filter(fn ($_, int $i) => $i !== $index);
}

public function shuffle(): OrderedListInterface
{
if (count($this->data) <= 1) {
return $this;
}

$data = $this->data;

do {
shuffle($data);
} while ($this->data === $data);

$instance = clone $this;
$instance->data = $data;

return $instance;
}
}
7 changes: 7 additions & 0 deletions src/OrderedListInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -264,4 +264,11 @@ public function prepend($value): self;
* @return OrderedListInterface<TValue>
*/
public function removeAt(int $index): self;

/**
* Shuffles all the values within the list.
*
* @return OrderedListInterface<TValue>
*/
public function shuffle(): self;
}
14 changes: 14 additions & 0 deletions tests/GenericOrderedListTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1473,4 +1473,18 @@ public function testWillRemoveItemAtSpecificPosition(): void
$list = $list->removeAt(1);
self::assertSame([1, 3], $list->toNativeArray());
}

public function testWillShuffleValuesInList(): void
{
$list = new GenericOrderedList([
1,
2,
3,
]);

$list2 = $list->shuffle();
self::assertSame([1, 2, 3], $list->toNativeArray());
self::assertNotSame($list, $list2);
self::assertNotSame([1, 2, 3], $list2->toNativeArray());
}
}

0 comments on commit d36e7b6

Please sign in to comment.