/
flatMap.php
51 lines (42 loc) · 1.25 KB
/
flatMap.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
<?php
namespace Idles;
use \Idles\Iterators\{
FlattenIteratorIterator,
MapRecursiveIterator,
MapRecursiveArrayIterator,
ValuesIterator
};
function _flatMapDepth(?iterable $collection, callable $iteratee, int $depth): iterable
{
$collection ??= [];
if (\is_array($collection)) {
$it = new FlattenIteratorIterator(new MapRecursiveArrayIterator($collection, $iteratee));
$it->setMaxDepth($depth);
return \iterator_to_array(new ValuesIterator($it), false);
}
$it = new FlattenIteratorIterator(new MapRecursiveIterator($collection, $iteratee));
$it->setMaxDepth($depth);
return new ValuesIterator($it);
}
function flatMap(...$args)
{
return curryN(2,
fn (callable $iteratee, ?iterable $collection) => _flatMapDepth($collection, $iteratee, 1)
)(...$args);
}
function chain(...$args)
{
return flatMap(...$args);
}
function flatMapDeep(...$args)
{
return curryN(2,
fn (callable $iteratee, ?iterable $collection) => _flatMapDepth($collection, $iteratee, \PHP_INT_MAX)
)(...$args);
}
function flatMapDepth(...$args)
{
return curryN(3,
fn (callable $iteratee, int $depth, ?iterable $collection) => _flatMapDepth($collection, $iteratee, $depth)
)(...$args);
}