Skip to content

Commit 2c87ba1

Browse files
aarcex3brendt
andauthored
feat (ArrayHelper): implement sort method. (#642)
Co-authored-by: Brent Roose <[email protected]>
1 parent 31497ad commit 2c87ba1

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

src/Tempest/Support/src/ArrayHelper.php

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -766,4 +766,15 @@ public function mapTo(string $to): self
766766
{
767767
return new self(map($this->array)->collection()->to($to));
768768
}
769+
770+
/**
771+
* Sorts the array in ascending order.
772+
*/
773+
public function sort(): self
774+
{
775+
$array = $this->array;
776+
sort($array);
777+
778+
return new self($array);
779+
}
769780
}

tests/Integration/Support/ArrayHelperTest.php

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
namespace Tests\Tempest\Integration\Support;
66

7+
use PHPUnit\Framework\Attributes\DataProvider;
78
use function Tempest\Support\arr;
89
use Tests\Tempest\Integration\FrameworkIntegrationTestCase;
910
use Tests\Tempest\Integration\Support\Fixtures\TestObject;
@@ -19,4 +20,26 @@ public function test_map_to(): void
1920

2021
$this->assertInstanceOf(TestObject::class, $array[0]);
2122
}
23+
24+
#[DataProvider('provide_sort_cases')]
25+
public function test_sort(array $input, array $expected): void
26+
{
27+
$array = arr($input)->sort()->toArray();
28+
$this->assertEquals($expected, $array);
29+
}
30+
31+
public static function provide_sort_cases(): iterable
32+
{
33+
return [
34+
"Regular case" => [[3, 1, 4, 1, 5, 9], [1, 1, 3, 4, 5, 9]],
35+
"Empty array" => [[], []],
36+
"Single element" => [[1], [1]],
37+
"All elements the same" => [[2, 2, 2], [2, 2, 2]],
38+
"Reverse order" => [[5, 4, 3, 2, 1], [1, 2, 3, 4, 5]],
39+
"Negative numbers" => [[-1, -3, -2, 0], [-3, -2, -1, 0]],
40+
"Mixed positive and negative" => [[3, -1, 4, 1, -5, 9], [-5, -1, 1, 3, 4, 9]],
41+
"Strings" => [['apple', 'orange', 'banana'], ['apple', 'banana', 'orange']],
42+
"Large array" => [range(1000, 1, -1), range(1, 1000)],
43+
];
44+
}
2245
}

0 commit comments

Comments
 (0)