Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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()
--------------

Expand Down
27 changes: 27 additions & 0 deletions src/iterable-functions.php
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,33 @@ function iterable_filter($iterable, $filter = null)

}

if (!function_exists('iterable_reduce')) {
/**
* Reduces an iterable.
*
* @param iterable<mixed> $iterable
* @param callable(mixed, mixed) $reduce
* @return mixed
*
* @psalm-template TValue
* @psalm-template TResult
*
* @psalm-param iterable<TValue> $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
Expand Down
24 changes: 24 additions & 0 deletions tests/TestIterableReduce.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?php

use PHPUnit\Framework\TestCase;

final class TestIterableReduce extends TestCase
{
public function testArrayReduce()
{
$iterable = array(1, 2);
$reduce = static function ($carry, $item) {
return $carry + $item;
};
self::assertSame(3, iterable_reduce($iterable, $reduce, 0));
}

public function testTraversableReduce()
{
$iterable = SplFixedArray::fromArray(array(1, 2));
$reduce = static function ($carry, $item) {
return $carry + $item;
};
self::assertSame(3, iterable_reduce($iterable, $reduce, 0));
}
}