Skip to content

Commit be860ef

Browse files
authored
Merge pull request #17 from samsonasik/add-limit
[Finder] Add ability to gather only limited found data on Finder::rows()
2 parents f86a0e1 + 0e257ee commit be860ef

File tree

3 files changed

+41
-4
lines changed

3 files changed

+41
-4
lines changed

README.md

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -356,4 +356,14 @@ var_dump(Finder::rows(
356356
$data,
357357
static fn($datum, $key): bool => $datum > 6 && $key > 1
358358
)); // [8, 9]
359+
360+
361+
// WITH gather only limited found data
362+
$data = [1, 2];
363+
$filter = static fn($datum): bool => $datum >= 0;
364+
$limit = 1;
365+
366+
var_dump(
367+
Finder::rows($data, $filter, limit: $limit)
368+
); // [1]
359369
```

src/Finder.php

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -123,10 +123,15 @@ public static function last(
123123
* @param callable(mixed $datum, int|string|null $key=): bool $filter
124124
* @return mixed[]
125125
*/
126-
public static function rows(iterable $data, callable $filter, bool $preserveKey = false): array
127-
{
128-
$rows = [];
129-
$newKey = 0;
126+
public static function rows(
127+
iterable $data,
128+
callable $filter,
129+
bool $preserveKey = false,
130+
?int $limit = null
131+
): array {
132+
$rows = [];
133+
$newKey = 0;
134+
$totalFound = 0;
130135

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

148153
$rows[$rowKey] = $datum;
154+
155+
if ($limit === null) {
156+
continue;
157+
}
158+
159+
++$totalFound;
160+
if ($totalFound === $limit) {
161+
break;
162+
}
149163
}
150164

151165
return $rows;

tests/FinderTest.php

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -323,4 +323,17 @@ public static function rowsDataProviderPreserveKey(): array
323323
],
324324
];
325325
}
326+
327+
public function testRowsWithLimit(): void
328+
{
329+
$data = [1, 2];
330+
$filter = static fn ($datum): bool => $datum >= 0;
331+
332+
$this->assertSame(
333+
[
334+
1,
335+
],
336+
Finder::rows($data, $filter, limit: 1)
337+
);
338+
}
326339
}

0 commit comments

Comments
 (0)