Skip to content

Instantly share code, notes, and snippets.

@italolelis
Last active July 14, 2016 20:43
Show Gist options
  • Save italolelis/2712c6c671b50864748b to your computer and use it in GitHub Desktop.
Save italolelis/2712c6c671b50864748b to your computer and use it in GitHub Desktop.
FlatMap implementation in PHP, following the Reactive Extensions intiative
function flatMap($data, \Closure $p)
{
$collection = call_user_func_array("array_map", array($p));
return iterator_to_array(new \RecursiveIteratorIterator(
new \RecursiveArrayIterator($data)), false);
}
@miguelsaddress
Copy link

what is $collection doing?
https://gist.github.com/italolelis/2712c6c671b50864748b#file-flatmap-php-L3

How could you deal with nested elements?

$col = new MyCollection(1, 2, 3, new MyCollection(4, 5, 6), 7, 8, new MyCollection(9));

To obtain:

$res = $col->flatMap(function($x) {
    return array($x, $x+1);
});

$res ===> [1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment