Skip to content

Commit

Permalink
Merge pull request #6 from simPod/reduce
Browse files Browse the repository at this point in the history
Introduce iterable_reduce()
  • Loading branch information
bpolaszek authored May 1, 2020
2 parents 8a0f64f + 604696e commit 82996c6
Show file tree
Hide file tree
Showing 3 changed files with 71 additions and 0 deletions.
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));
}
}

0 comments on commit 82996c6

Please sign in to comment.