diff --git a/README.md b/README.md index 7e972ce..1bb43b4 100644 --- a/README.md +++ b/README.md @@ -72,6 +72,26 @@ foreach (iterable_map($generator(), 'strtoupper') as $item) { } ``` +iterable_reduce() +-------------- + +Works like an `reduce` with an `iterable`. + +```php +$generator = function () { + yield 1; + yield 2; +}; + +$reduce = static function ($carry, $item) { + return $carry + $item; +}; + +var_dump( + iterable_reduce($generator(), $reduce, 0)) +); // 3 +``` + iterable_filter() -------------- diff --git a/src/iterable-functions.php b/src/iterable-functions.php index b787853..de15eeb 100644 --- a/src/iterable-functions.php +++ b/src/iterable-functions.php @@ -105,6 +105,33 @@ function iterable_filter($iterable, $filter = null) } +if (!function_exists('iterable_reduce')) { + /** + * Reduces an iterable. + * + * @param iterable $iterable + * @param callable(mixed, mixed) $reduce + * @return mixed + * + * @psalm-template TValue + * @psalm-template TResult + * + * @psalm-param iterable $iterable + * @psalm-param callable(TResult|null, TValue) $reduce + * @psalm-param TResult|null $initial + * + * @psalm-return TResult|null + */ + function iterable_reduce($iterable, $reduce, $initial = null) + { + foreach ($iterable as $item) { + $initial = $reduce($initial, $item); + } + + return $initial; + } +} + /** * @param iterable|array|\Traversable $iterable * @param callable|null $filter diff --git a/tests/TestIterableReduce.php b/tests/TestIterableReduce.php new file mode 100644 index 0000000..99b7709 --- /dev/null +++ b/tests/TestIterableReduce.php @@ -0,0 +1,24 @@ +