Skip to content

Commit 448e3a9

Browse files
committed
Add contains function
1 parent c7588a1 commit 448e3a9

File tree

3 files changed

+57
-0
lines changed

3 files changed

+57
-0
lines changed

composer.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@
6666
"src/Fp/Functions/Collection/FlatMap.php",
6767
"src/Fp/Functions/Collection/Traverse.php",
6868
"src/Fp/Functions/Collection/Sequence.php",
69+
"src/Fp/Functions/Collection/Contains.php",
6970
"src/Fp/Functions/Collection/Fold.php",
7071
"src/Fp/Functions/Collection/Tap.php",
7172
"src/Fp/Functions/Collection/GroupBy.php",
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Fp\Collection;
6+
7+
/**
8+
* Checks if a value exists in an array.
9+
*
10+
* ```php
11+
* >>> contains(42, [40, 41, 42]);
12+
* => true
13+
* >>> contains(43, [40, 41, 42]);
14+
* => false
15+
* ```
16+
*/
17+
function contains(mixed $elem, iterable $collection): bool
18+
{
19+
/** @var mixed $item */
20+
foreach ($collection as $item) {
21+
if ($item === $elem) {
22+
return true;
23+
}
24+
}
25+
26+
return false;
27+
}
28+
29+
/**
30+
* Varargs version of {@see contains()}
31+
*/
32+
function containsT(mixed $elem, mixed ...$items): bool
33+
{
34+
return contains($elem, $items);
35+
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Tests\Runtime\Functions\Collection;
6+
7+
use PHPUnit\Framework\TestCase;
8+
9+
use function Fp\Collection\contains;
10+
use function Fp\Collection\containsT;
11+
12+
final class ContainsTest extends TestCase
13+
{
14+
public function testContains(): void
15+
{
16+
$this->assertTrue(contains(42, [40, 41, 42]));
17+
$this->assertFalse(contains(43, [40, 41, 42]));
18+
$this->assertTrue(containsT(42, 40, 41, 42));
19+
$this->assertFalse(containsT(43, 40, 41, 42));
20+
}
21+
}

0 commit comments

Comments
 (0)