Skip to content

Instantly share code, notes, and snippets.

@bcremer
Last active September 2, 2020 05:33
Show Gist options
  • Save bcremer/2d056761019c5119328ff33cefb157db to your computer and use it in GitHub Desktop.
Save bcremer/2d056761019c5119328ff33cefb157db to your computer and use it in GitHub Desktop.
<?php
declare(strict_types=1);
/**
* @psalm-template TKey
* @psalm-template TValue
* @psalm-param iterable<TKey, TValue> $list
* @psalm-param callable(TValue): bool $filter
* @psalm-return Generator<TKey, TValue>
*/
function iterable_filter(iterable $list, callable $filter): Generator
{
foreach ($list as $k => $v) {
if ($filter($v)) {
yield $k => $v;
}
}
}
/**
* @psalm-template TKey
* @psalm-template TValue
* @psalm-template TCallableReturn
* @psalm-param iterable<TKey, TValue> $list
* @psalm-param callable(TKey, TValue): TCallableReturn $operation
* @psalm-return Generator<TKey,TCallableReturn>
*/
function iterable_map(iterable $list, callable $operation): Generator
{
foreach ($list as $k => $v) {
yield $k => $operation($k, $v);
}
}
/**
* @psalm-template TKey
* @psalm-template TValue
* @psalm-param iterable<TKey, TValue> $collection
* @psalm-param callable(TValue, TKey): string $callback
* @psalm-return Generator<TKey, TValue>
*/
function iterable_unique(iterable $collection, callable $callback): Generator
{
$keys = [];
foreach ($collection as $key => $element) {
$index = $callback($element, $key);
if (!array_key_exists($index, $keys)) {
$keys[$index] = null;
yield $key => $element;
}
}
}
$list = [
'faz' => new \DateTime('tomorrow'),
'foo' => new \DateTime('now'),
'baz' => new \DateTime('1989-01-01'),
'bar' => new \DateTime('tomorrow'),
'bafr' => new \DateTime('next week'),
];
$list = iterable_unique($list, static function(\DateTime $value) : string {
return $value->format('Ymd');
});
$list = iterable_filter($list, static function (\DateTime $value) : bool {
return $value->format('Y') > 2000;
});
$list = iterable_map($list, static function (string $_, \DateTime $value) : int{
return (int)$value->format('Y');
});
foreach ($list as $key => $value) {
echo "$key:$value\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment