<?php
// Everything you enter here will be executed by our servers. Try it!
function iterator_compose()
{
foreach (array_reverse(func_get_args()) as $it) {
$prev = null;
if (is_callable($it)) {
$prev = $it($prev);
} else if (is_object($it)) {
$prev = $it;
} else {
$prev = new $it($prev);
}
}
return $prev;
}
function cycle($it)
{
$saved = [];
foreach ($it as $key => $val) {
$saved[] = $val;
yield $val;
}
while ($saved) {
foreach ($saved as $val) {
yield $val;
}
}
}
function limit($it, $count, $offset = 0)
{
return new LimitIterator($it, $offset, $count);
}
function iterator_chunk(\Traversable $it, $chunkSize)
{
$it->rewind();
$chunk = [];
$steps = range(0, $chunkSize);
while (true) {
foreach ($steps as $_) {
if (!$it->valid()) {
break 2;
}
$chunk[] = $it->current();
$it->next();
}
yield $chunk;
$chunk = [];
}
if ($chunk) {
yield $chunk;
}
}
$it = iterator_chunk(
new ArrayIterator(range(0, 125))
, 32);
$colors = new ArrayIterator(['red', 'green', 'blue']);
foreach (limit(cycle($colors), 10) as $color) {
echo "$color\n";
}
foreach ($it as $i => $c) {
echo "====== Chunk $i ======\n";
var_export($c);
echo "\n";
}
preferences:
32.24 ms | 402 KiB | 5 Q