Skip to content

Commit e73bc9e

Browse files
Copilotvoku
andauthored
Add findKey method with TDD tests for finding index of min/max element via callable
Agent-Logs-Url: https://github.com/voku/Arrayy/sessions/9727c001-36d7-4c06-865e-c0a76fd5012f Co-authored-by: voku <264695+voku@users.noreply.github.com>
1 parent e2d82c3 commit e73bc9e

2 files changed

Lines changed: 69 additions & 0 deletions

File tree

src/Arrayy.php

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2748,6 +2748,36 @@ public function find(\Closure $closure)
27482748
return false;
27492749
}
27502750

2751+
/**
2752+
* Find the key of the first item in an array that passes the truth test, otherwise return false.
2753+
*
2754+
* EXAMPLE: <code>
2755+
* $search = 'foo';
2756+
* $closure = function ($value, $key) use ($search) {
2757+
* return $value === $search;
2758+
* };
2759+
* a(['foo', 'bar', 'lall'])->findKey($closure); // 0
2760+
* </code>
2761+
*
2762+
* @param \Closure $closure
2763+
*
2764+
* @return false|int|string
2765+
* <p>Return false if we did not find the key.</p>
2766+
*
2767+
* @phpstan-param \Closure(T,TKey):bool $closure
2768+
* @phpstan-return TKey|false
2769+
*/
2770+
public function findKey(\Closure $closure)
2771+
{
2772+
foreach ($this->getGenerator() as $key => $value) {
2773+
if ($closure($value, $key)) {
2774+
return $key;
2775+
}
2776+
}
2777+
2778+
return false;
2779+
}
2780+
27512781
/**
27522782
* find by ...
27532783
*

tests/ArrayyTest.php

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3223,6 +3223,45 @@ public function testFind($array, $search, $result)
32233223
static::assertSame($result, $resultMatch, 'tested:' . \print_r($array, true));
32243224
}
32253225

3226+
/**
3227+
* @return array
3228+
*/
3229+
public function findKeyProvider(): array
3230+
{
3231+
return [
3232+
[[], null, false],
3233+
[[false], false, 0],
3234+
[[true], true, 0],
3235+
[[-9, 1, 2], -9, 0],
3236+
[[-9, 1, 2], 1, 1],
3237+
[[-9, 1, 2], 2, 2],
3238+
[[-9, 1, 2], 99, false],
3239+
[[1.18], 1.18, 0],
3240+
[['string', 'foo', 'lall'], 'foo', 1],
3241+
[['a' => 'foo', 'b' => 'bar'], 'bar', 'b'],
3242+
[['a' => 'foo', 'b' => 'bar'], 'baz', false],
3243+
];
3244+
}
3245+
3246+
/**
3247+
* @dataProvider findKeyProvider()
3248+
*
3249+
* @param array $array
3250+
* @param mixed $search
3251+
* @param false|mixed $result
3252+
*/
3253+
public function testFindKey($array, $search, $result)
3254+
{
3255+
$closure = static function ($value) use ($search) {
3256+
return $value === $search;
3257+
};
3258+
3259+
$arrayy = A::create($array);
3260+
$resultMatch = $arrayy->findKey($closure);
3261+
3262+
static::assertSame($result, $resultMatch, 'tested:' . \print_r($array, true));
3263+
}
3264+
32263265
/**
32273266
* @dataProvider firstProvider()
32283267
*

0 commit comments

Comments
 (0)