Last active
April 16, 2017 13:10
-
-
Save haampie/3cbfe7651637b81cf8cdf2c96c30940a to your computer and use it in GitHub Desktop.
better_collections.php
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function take(Iterator $it, int $n) { | |
for ($i = 0; $i < $n && $it->valid(); $i++, $it->next()) { | |
yield $it->current(); | |
} | |
} | |
function filter(Iterator $it, callable $f) { | |
foreach ($it as $item) { | |
if ($f($item)) { | |
yield $item; | |
} | |
} | |
} | |
function map(Iterator $it, callable $f) { | |
foreach ($it as $item) { | |
yield $f($item); | |
} | |
} | |
function flat_map(Iterator $it, callable $f) { | |
foreach ($it as $item) { | |
yield from $f($item); | |
} | |
} | |
function skip(Iterator $it, int $n) { | |
for ($i = 0; $i < $n && $it->valid(); $i++, $it->next()); | |
for (; $it->valid(); $it->next()) { | |
yield $it->current(); | |
} | |
} | |
function skip_while(Iterator $it, callable $f) { | |
for (; $it->valid() && $f($it->current()); $it->next()); | |
for (; $it->valid(); $it->next()) { | |
yield $it->current(); | |
} | |
} | |
function paginate(Iterator $it, int $n) { | |
while($it->valid()) { | |
yield take($it, $n); | |
} | |
} | |
function take_while(Iterator $it, callable $f) { | |
for (; $it->valid() && $f($it->current()); $it->next()) { | |
yield $it->current(); | |
} | |
} | |
function slice(Iterator $it, int $offset, int $length) { | |
return take(skip($it, $offset), $length); | |
} | |
function scan(Iterator $it, $initial, callable $f) { | |
$carry = $initial; | |
foreach($it as $item) { | |
$carry = $f($carry, $item); | |
yield $carry; | |
} | |
} | |
function fold(Iterator $it, $acc, callable $f) { | |
foreach ($it as $value) { | |
$acc = $f($acc, $value); | |
} | |
return $acc; | |
} | |
function zip(Iterator $left, Iterator $right) { | |
for (; $left->valid() && $right->valid(); $left->next(), $right->next()) { | |
yield [$left->current(), $right->current()]; | |
} | |
} | |
function groupBy(Iterator $it, callable $f) { | |
while($it->valid()){ | |
$current = $it->current(); | |
yield take_while($it, function($item) use ($f, $current) { | |
return $f($current, $item); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment