Skip to content

Commit e601979

Browse files
committed
Add iter\recurse()
1 parent 82409a6 commit e601979

File tree

3 files changed

+40
-0
lines changed

3 files changed

+40
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,7 @@ list the function signatures as an overview:
7373
void apply(callable $function, iterable $iterable)
7474
string join(string $separator, iterable $iterable)
7575
int count(iterable $iterable)
76+
mixed recurse(callable $function, $iterable)
7677
array toArray(iterable $iterable)
7778
array toArrayWithKeys(iterable $iterable)
7879
bool isIterable($value)

src/iter.php

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -838,6 +838,30 @@ function count($iterable) {
838838
return $count;
839839
}
840840

841+
/**
842+
* Recursively applies a function, working on entire iterables rather than
843+
* individual values.
844+
*
845+
* The function will be called both on the passed iterable and all iterables it
846+
* contains, etc. The call sequence is in post-order (inner before outer).
847+
*
848+
* Examples:
849+
*
850+
* iter\recurse('iter\toArray',
851+
* new ArrayIterator([1, 2, new ArrayIterator([3, 4])]));
852+
* => [1, 2, [3, 4]]
853+
*
854+
* @param callable $function
855+
* @param $iterable
856+
* @return mixed
857+
*/
858+
function recurse(callable $function, $iterable) {
859+
_assertIterable($iterable, 'Second argument');
860+
return $function(map(function($value) use($function) {
861+
return isIterable($value) ? recurse($function, $value) : $value;
862+
}, $iterable));
863+
}
864+
841865
/**
842866
* Converts any iterable into an Iterator.
843867
*

test/iterTest.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -381,6 +381,21 @@ function() {
381381
);
382382
}
383383

384+
function testRecurse() {
385+
$iter = new \ArrayIterator(['a' => 1, 'b' => 2,
386+
'c' => new \ArrayIterator(['d' => 3, 'e' => 4])]);
387+
388+
$this->assertSame(
389+
[1, 2, [3, 4]],
390+
recurse('iter\toArray', $iter)
391+
);
392+
393+
$this->assertSame(
394+
['a' => 1, 'b' => 2, 'c' => ['d' => 3, 'e' => 4]],
395+
recurse('iter\toArrayWithKeys', $iter)
396+
);
397+
}
398+
384399
private function assertKeysValues(array $keys, array $values, callable $fn) {
385400
$this->assertSame($keys, toArray(keys($fn())));
386401
$this->assertSame($values, toArray(values($fn())));

0 commit comments

Comments
 (0)