Quantcast
Channel: Recent Gists from assertchris
Viewing all articles
Browse latest Browse all 30

flatMap.php

$
0
0
flatMap.php
<?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)
)
);

Viewing all articles
Browse latest Browse all 30

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>