Skip to content

Commit fff1450

Browse files
committed
Merge pull request bocharsky-bw#10 from talyssonoc/implement_find_method
Implement find method
2 parents 5ebb0e5 + 18c1ecc commit fff1450

File tree

4 files changed

+57
-0
lines changed

4 files changed

+57
-0
lines changed

README.md

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -405,6 +405,15 @@ $a->filter(function($value) {
405405
$a->toArray(); // [0 => 'a', 2 => 'b']
406406
```
407407

408+
### find
409+
410+
``` php
411+
$a = MutableArray::create([4, 3, 2, 1]);
412+
$value = $a->find(function($value, $key, $array) {
413+
return ($value % 2) === 0;
414+
});
415+
$value // 4
416+
408417
### first
409418

410419
``` php

src/AbstractArray.php

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -640,4 +640,22 @@ protected function sortingKeys(array &$elements, $order = SORT_ASC, $strategy =
640640
ksort($elements, $strategy);
641641
}
642642
}
643+
644+
/**
645+
* Returns the first value that matches $func condition
646+
*
647+
* @param Closure $func
648+
*
649+
* @return mixed The resulting value
650+
*/
651+
public function find(Closure $func)
652+
{
653+
foreach ($this->elements as $key => $value) {
654+
if($func($value, $key)) {
655+
return $value;
656+
}
657+
}
658+
659+
return null;
660+
}
643661
}

tests/ImmutableArrayTest.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -451,6 +451,21 @@ public function testFilter(array $array)
451451
$this->assertTrue($filteredArray === $copiedMa->toArray());
452452
}
453453

454+
public function testFind()
455+
{
456+
$callable = function($value) {
457+
return 2 === $value;
458+
};
459+
460+
$array = ['a', 'key' => 0, 2, 'hello'];
461+
462+
$a = new ImmutableArray($array);
463+
464+
$found = $a->find($callable);
465+
466+
$this->assertTrue($found === 2);
467+
}
468+
454469
/**
455470
* @dataProvider simpleArrayProvider
456471
*/

tests/MutableArrayTest.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -468,6 +468,21 @@ public function testFilter(array $array)
468468
$this->assertTrue($filteredArray === $ma->toArray());
469469
}
470470

471+
public function testFind()
472+
{
473+
$callable = function($value) {
474+
return 2 === $value;
475+
};
476+
477+
$array = ['a', 'key' => 0, 2, 'hello'];
478+
479+
$a = new MutableArray($array);
480+
481+
$found = $a->find($callable);
482+
483+
$this->assertTrue($found === 2);
484+
}
485+
471486
/**
472487
* @dataProvider simpleArrayProvider
473488
*/

0 commit comments

Comments
 (0)