Skip to content

Commit fd8e910

Browse files
authored
feat: introduce iterable.find (#8)
1 parent 0bec4d3 commit fd8e910

File tree

5 files changed

+76
-1
lines changed

5 files changed

+76
-1
lines changed

README.md

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,3 +18,18 @@ match ($val) {
1818
default => noop(),
1919
};
2020
```
21+
22+
## Iterable
23+
24+
### find()
25+
26+
Finds a value in an iterable.
27+
28+
```php
29+
use function Cdn77\Functions\Iterable\find;
30+
31+
$iterable = [0, 1, 2, 3];
32+
$option = find($iterable, static fn (mixed $_, int $value) => $value < 2);
33+
34+
assert($option->get() === 0);
35+
```

composer.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,8 @@
2020
],
2121
"require": {
2222
"php": "^8.0",
23-
"ext-ds": "*"
23+
"ext-ds": "*",
24+
"phpoption/phpoption": "^1.9"
2425
},
2526
"require-dev": {
2627
"cdn77/coding-standard": "^6.0",

src/functions_include.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,5 +5,6 @@
55
require_once __DIR__ . '/absurd.php';
66
require_once __DIR__ . '/ds.php';
77
require_once __DIR__ . '/generator.php';
8+
require_once __DIR__ . '/iterable.php';
89
require_once __DIR__ . '/never.php';
910
require_once __DIR__ . '/noop.php';

src/iterable.php

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Cdn77\Functions\Iterable;
6+
7+
use PhpOption\None;
8+
use PhpOption\Option;
9+
use PhpOption\Some;
10+
11+
/**
12+
* @param iterable<K, T> $iterable
13+
* @param callable(K, T): bool $filterFn
14+
*
15+
* @return Option<T>
16+
*
17+
* @template K
18+
* @template T
19+
*/
20+
function find(iterable $iterable, callable $filterFn): Option
21+
{
22+
foreach ($iterable as $k => $v) {
23+
if ($filterFn($k, $v)) {
24+
return new Some($v);
25+
}
26+
}
27+
28+
return None::create();
29+
}

tests/IterableTest.php

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Cdn77\Functions\Tests;
6+
7+
use PhpOption\None;
8+
use PHPUnit\Framework\TestCase;
9+
10+
use function Cdn77\Functions\Iterable\find;
11+
12+
final class IterableTest extends TestCase
13+
{
14+
public function testFindFirst(): void
15+
{
16+
$iterable = [0, 1, 2, 3];
17+
$option = find($iterable, static fn (mixed $_, int $value) => $value < 2);
18+
19+
self::assertSame(0, $option->getOrElse(null));
20+
}
21+
22+
public function testDontFind(): void
23+
{
24+
$iterable = [0, 1, 2, 3];
25+
$option = find($iterable, static fn (mixed $_, int $value) => $value > 3);
26+
27+
self::assertSame(None::create(), $option);
28+
}
29+
}

0 commit comments

Comments
 (0)