sort($data); $this->assertEquals([], $data); } /** * Confirm that sorting an array of integers works. */ public function testSortingIntegers() { $data = [3, 1, 4, 1, 5, 9]; $sorter = new Sorter(fn ($a, $b) => $a <=> $b); $sorter->sort($data); $this->assertEquals([1, 1, 3, 4, 5, 9], $data); } /** * Confirm that sorting an array of strings works. */ public function testSortingStrings() { $data = ['apple', 'banana', 'cherry', 'date', 'elderberry']; $sorter = new Sorter(fn ($a, $b) => strcmp($a, $b)); $sorter->sort($data); $this->assertEquals(['apple', 'banana', 'cherry', 'date', 'elderberry'], $data); } /** * Confirm that sorting an array of strings by length works. */ public function testSortingByLength() { $data = ['apple', 'banana', 'cherry', 'date', 'elderberry']; $sorter = new Sorter(fn ($a, $b) => strlen($a) <=> strlen($b)); $sorter->sort($data); $this->assertEquals(['date', 'apple', 'banana', 'cherry', 'elderberry'], $data); } /** * Confirm that sorting an array of strings by length works with a second comparison * using strcmp to sort alphabetically in the case of a tie. */ public function testSortingByLengthWithTieBreaker() { $data = ['cc', 'c', 'ccc', 'aaa', 'aa', 'a', 'b', 'bb', 'bbb']; $sorter = new Sorter( fn ($a, $b) => strlen($a) <=> strlen($b), fn ($a, $b) => strcmp($a, $b) ); $sorter->sort($data); $this->assertEquals(['a', 'b', 'c', 'aa', 'bb', 'cc', 'aaa', 'bbb', 'ccc'], $data); } /** * Confirm that adding sorters using addSorter() works as expected. */ public function testAddingSorters() { $data = ['cc', 'c', 'ccc', 'aaa', 'aa', 'a', 'b', 'bb', 'bbb']; $sorter = new Sorter(); $sorter->addComparison( fn ($a, $b) => strlen($a) <=> strlen($b), fn ($a, $b) => strcmp($a, $b) ); $sorter->sort($data); $this->assertEquals(['a', 'b', 'c', 'aa', 'bb', 'cc', 'aaa', 'bbb', 'ccc'], $data); } }