Last active
June 30, 2016 01:57
-
-
Save assertchris/6dd66348650bf3a469cea07f5a0b2ece to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
function is_iterable($value) { | |
return is_array($value) || $value instanceof Traversable; | |
} | |
function flatMap(/* iterable */ $iterable, callable $callable) { | |
foreach ($iterable as $value) { | |
if (is_iterable($value)) { | |
foreach (flatMap($value, $callable) as $next) { | |
yield $next; | |
} | |
} else { | |
yield $callable($value); | |
} | |
} | |
} | |
$callable = function($value) { | |
print "value: {$value}\n"; | |
return $value * 2; | |
}; | |
$one = [1, 2, 3]; | |
print_r( | |
iterator_to_array( | |
flatMap($one, $callable) | |
) | |
); | |
$two = [1, [2, 3], 4]; | |
print_r( | |
iterator_to_array( | |
flatMap($two, $callable) | |
) | |
); | |
$three = [1, [2, 3, new ArrayIterator([4])], 5]; | |
print_r( | |
iterator_to_array( | |
flatMap($three, $callable) | |
) | |
); |
Thanks for the tip. In that case, I definitely prefer not to use yield from
. I don't think the relatively small performance hit is worth the caveat of duplicate indices.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
iterator_to_array()
preserves keys by default. Usingiterator_to_array(flatMap(...), false)
works as expected.yield from
results in duplicate keys.