Flatten array

This commit is contained in:
Oliver Davies 2020-07-12 16:05:33 +01:00
parent 3171da146f
commit fee5c1afe4
4 changed files with 52 additions and 0 deletions

View file

@ -5,6 +5,7 @@ PHP code katas, tested with [Pest PHP][]. Based on exercises from [Exercism.io][
Includes: Includes:
- **Anagrams**: select an anagram for a word from a list of condidates. - **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. - **Bob**: returns different responses based on input.
- **Bowling**: calculate the score for a game of bowling. - **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. - **Grade School**: given students' names along with the grade that they are in, create a roster for the school.

View file

@ -10,6 +10,7 @@
"phpunit/phpunit": "^9.0" "phpunit/phpunit": "^9.0"
}, },
"autoload": { "autoload": {
"files": ["src/FlattenArray.php"],
"psr-4": { "psr-4": {
"App\\": "src/" "App\\": "src/"
} }

19
src/FlattenArray.php Normal file
View 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));
}

View 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' => [],
]
]);