|
17 | 17 | use stdClass; |
18 | 18 |
|
19 | 19 | use function current; |
| 20 | +use function is_string; |
20 | 21 | use function str_contains; |
21 | 22 |
|
22 | 23 | final class FinderTest extends TestCase |
@@ -382,4 +383,76 @@ public function testRowsWithLimit(): void |
382 | 383 | Finder::rows($data, $filter, limit: 1) |
383 | 384 | ); |
384 | 385 | } |
| 386 | + |
| 387 | + /** |
| 388 | + * @param array<int|string, mixed> $expectedMatching |
| 389 | + * @param array<int|string, mixed> $expectedNotMatching |
| 390 | + * @param array<int|string, int|string> $data |
| 391 | + */ |
| 392 | + #[DataProvider('partitionDataProvider')] |
| 393 | + public function testPartition( |
| 394 | + iterable $data, |
| 395 | + callable $filter, |
| 396 | + array $expectedMatching, |
| 397 | + array $expectedNotMatching, |
| 398 | + bool $preserveKey = false |
| 399 | + ): void { |
| 400 | + [$matching, $notMatching] = Finder::partition($data, $filter, $preserveKey); |
| 401 | + |
| 402 | + $this->assertSame($expectedMatching, $matching); |
| 403 | + $this->assertSame($expectedNotMatching, $notMatching); |
| 404 | + } |
| 405 | + |
| 406 | + /** |
| 407 | + * @return Iterator<string, array{iterable, callable, array<int|string, mixed>, array<int|string, mixed>, bool}> |
| 408 | + */ |
| 409 | + public static function partitionDataProvider(): Iterator |
| 410 | + { |
| 411 | + yield 'partition numbers greater than 5' => [ |
| 412 | + [1, 6, 3, 8, 4, 9], |
| 413 | + static fn($datum): bool => $datum > 5, |
| 414 | + [6, 8, 9], |
| 415 | + [1, 3, 4], |
| 416 | + false, |
| 417 | + ]; |
| 418 | + |
| 419 | + yield 'partition numbers with preserved keys' => [ |
| 420 | + [1, 6, 3, 8, 4, 9], |
| 421 | + static fn($datum): bool => $datum > 5, |
| 422 | + [1 => 6, 3 => 8, 5 => 9], |
| 423 | + [0 => 1, 2 => 3, 4 => 4], |
| 424 | + true, |
| 425 | + ]; |
| 426 | + |
| 427 | + yield 'partition using key in filter' => [ |
| 428 | + [10, 20, 30, 40], |
| 429 | + static fn($datum, $key): bool => $key % 2 === 0, |
| 430 | + [0 => 10, 2 => 30], |
| 431 | + [1 => 20, 3 => 40], |
| 432 | + true, |
| 433 | + ]; |
| 434 | + |
| 435 | + yield 'partition associative array' => [ |
| 436 | + ['name' => 'John', 'age' => 25, 'city' => 'NYC', 'score' => 100], |
| 437 | + static fn($datum): bool => is_string($datum), |
| 438 | + ['name' => 'John', 'city' => 'NYC'], |
| 439 | + ['age' => 25, 'score' => 100], |
| 440 | + false, |
| 441 | + ]; |
| 442 | + } |
| 443 | + |
| 444 | + public function testPartitionPreservesOriginalData(): void |
| 445 | + { |
| 446 | + $data = [1, 2, 3]; |
| 447 | + $copy = $data; |
| 448 | + |
| 449 | + [$matching, $notMatching] = Finder::partition( |
| 450 | + $data, |
| 451 | + static fn($datum): bool => $datum > 1 |
| 452 | + ); |
| 453 | + |
| 454 | + $this->assertSame([2, 3], $matching); |
| 455 | + $this->assertSame([1], $notMatching); |
| 456 | + $this->assertSame($copy, $data); |
| 457 | + } |
385 | 458 | } |
0 commit comments