Flatten array
This commit is contained in:
parent
3171da146f
commit
fee5c1afe4
|
@ -5,6 +5,7 @@ PHP code katas, tested with [Pest PHP][]. Based on exercises from [Exercism.io][
|
|||
Includes:
|
||||
|
||||
- **Anagrams**: select an anagram for a word from a list of condidates.
|
||||
- **Flatten Array**: take a nested list and return a single flattened list with all values except nil/null.
|
||||
- **Bob**: returns different responses based on input.
|
||||
- **Bowling**: calculate the score for a game of bowling.
|
||||
- **Grade School**: given students' names along with the grade that they are in, create a roster for the school.
|
||||
|
|
|
@ -10,6 +10,7 @@
|
|||
"phpunit/phpunit": "^9.0"
|
||||
},
|
||||
"autoload": {
|
||||
"files": ["src/FlattenArray.php"],
|
||||
"psr-4": {
|
||||
"App\\": "src/"
|
||||
}
|
||||
|
|
19
src/FlattenArray.php
Normal file
19
src/FlattenArray.php
Normal file
|
@ -0,0 +1,19 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App;
|
||||
|
||||
function flattenArray(array $input, array &$output = []): array
|
||||
{
|
||||
foreach ($input as $item) {
|
||||
if (!is_array($item)) {
|
||||
$output[] = $item;
|
||||
continue;
|
||||
}
|
||||
|
||||
flattenArray($item, $output);
|
||||
}
|
||||
|
||||
return array_values(array_filter($output));
|
||||
}
|
31
tests/FlattenArrayTest.php
Normal file
31
tests/FlattenArrayTest.php
Normal file
|
@ -0,0 +1,31 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use function App\flattenArray;
|
||||
|
||||
it('flattens an array', function (
|
||||
array $input,
|
||||
array $expected
|
||||
): void {
|
||||
$result = flattenArray($input);
|
||||
|
||||
assertSame($expected, $result);
|
||||
})->with([
|
||||
[
|
||||
'input' => [1, 2, 3],
|
||||
'expected' => [1, 2, 3],
|
||||
],
|
||||
[
|
||||
'input' => [1, [2, 3, null, 4], [null], 5],
|
||||
'expected' => [1, 2, 3, 4, 5],
|
||||
],
|
||||
[
|
||||
'input' => [1, [2, [[3]], [4, [[5]]], 6, 7], 8],
|
||||
'expected' => [1, 2, 3, 4, 5, 6, 7, 8],
|
||||
],
|
||||
[
|
||||
'input' => [null, [[[null]]], null, null, [[null, null], null], null],
|
||||
'expected' => [],
|
||||
]
|
||||
]);
|
Loading…
Reference in a new issue