Last active
October 8, 2018 21:07
-
-
Save pwm/e51e3b1019ec7283ac3687db965fde75 to your computer and use it in GitHub Desktop.
map list map list
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
declare(strict_types=1); | |
function mapToList(array $map): array | |
{ | |
$list = []; | |
foreach ($map as $k => $v) { | |
$list[] = \is_array($v) | |
? [$k, mapToList($v)] | |
: [$k, $v]; | |
} | |
return $list; | |
} | |
function listToMap(array $list): array | |
{ | |
return array_merge([], ...array_map(function (array $e): array { | |
return [ | |
$e[0] => \is_array($e[1]) | |
? listToMap($e[1]) | |
: $e[1], | |
]; | |
}, $list)); | |
} | |
\assert(mapToList([]) === []); | |
\assert(listToMap([]) === []); | |
\assert(listToMap(mapToList([])) === []); | |
\assert(mapToList(listToMap([])) === []); | |
// | |
\assert(mapToList(['a' => 'b']) === [['a', 'b']]); | |
\assert(listToMap([['a', 'b']]) === ['a' => 'b']); | |
\assert(listToMap(mapToList(['a' => 'b'])) === ['a' => 'b']); | |
\assert(mapToList(listToMap([['a', 'b']])) === [['a', 'b']]); | |
// | |
\assert(mapToList(['a' => ['b' => ['c' => 'd']]]) === [['a', [['b', [['c', 'd']]]]]]); | |
\assert(listToMap([['a', [['b', [['c', 'd']]]]]]) === ['a' => ['b' => ['c' => 'd']]]); | |
\assert(listToMap(mapToList(['a' => ['b' => ['c' => 'd']]])) === ['a' => ['b' => ['c' => 'd']]]); | |
\assert(mapToList(listToMap([['a', [['b', [['c', 'd']]]]]])) === [['a', [['b', [['c', 'd']]]]]]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment