Skip to content

Commit

Permalink
Merge pull request #17 from samsonasik/add-limit
Browse files Browse the repository at this point in the history
[Finder] Add ability to gather only limited found data on Finder::rows()
  • Loading branch information
samsonasik authored Mar 30, 2024
2 parents f86a0e1 + 0e257ee commit be860ef
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 4 deletions.
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -356,4 +356,14 @@ var_dump(Finder::rows(
$data,
static fn($datum, $key): bool => $datum > 6 && $key > 1
)); // [8, 9]


// WITH gather only limited found data
$data = [1, 2];
$filter = static fn($datum): bool => $datum >= 0;
$limit = 1;

var_dump(
Finder::rows($data, $filter, limit: $limit)
); // [1]
```
22 changes: 18 additions & 4 deletions src/Finder.php
Original file line number Diff line number Diff line change
Expand Up @@ -123,10 +123,15 @@ public static function last(
* @param callable(mixed $datum, int|string|null $key=): bool $filter
* @return mixed[]
*/
public static function rows(iterable $data, callable $filter, bool $preserveKey = false): array
{
$rows = [];
$newKey = 0;
public static function rows(
iterable $data,
callable $filter,
bool $preserveKey = false,
?int $limit = null
): array {
$rows = [];
$newKey = 0;
$totalFound = 0;

foreach ($data as $key => $datum) {
$isFound = $filter($datum, $key);
Expand All @@ -146,6 +151,15 @@ public static function rows(iterable $data, callable $filter, bool $preserveKey
}

$rows[$rowKey] = $datum;

if ($limit === null) {
continue;
}

++$totalFound;
if ($totalFound === $limit) {
break;
}
}

return $rows;
Expand Down
13 changes: 13 additions & 0 deletions tests/FinderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -323,4 +323,17 @@ public static function rowsDataProviderPreserveKey(): array
],
];
}

public function testRowsWithLimit(): void
{
$data = [1, 2];
$filter = static fn ($datum): bool => $datum >= 0;

$this->assertSame(
[
1,
],
Finder::rows($data, $filter, limit: 1)
);
}
}

0 comments on commit be860ef

Please sign in to comment.