Skip to content

Allow object keys #24

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Feb 4, 2021
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
7 changes: 2 additions & 5 deletions src/iterable-functions.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
use Traversable;

use function array_filter;
use function array_map;
use function array_values;
use function iterator_to_array;

Expand All @@ -23,11 +22,9 @@
*/
function iterable_map(iterable $iterable, callable $map): iterable
{
if ($iterable instanceof Traversable) {
return new ArrayIterator(array_map($map, iterator_to_array($iterable)));
foreach ($iterable as $key => $item) {
yield $key => $map($item);
}

return array_map($map, $iterable);
}

/**
Expand Down
22 changes: 22 additions & 0 deletions tests/IterableMapTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,17 @@

namespace BenTools\IterableFunctions\Tests;

use Generator;
use PHPUnit\Framework\Assert;
use SplFixedArray;
use stdClass;

use function BenTools\IterableFunctions\iterable_map;
use function BenTools\IterableFunctions\iterable_to_array;
use function it;
use function PHPUnit\Framework\assertEquals;
use function PHPUnit\Framework\assertInstanceOf;
use function PHPUnit\Framework\assertSame;

it('maps an array', function (): void {
$iterable = ['foo', 'bar'];
Expand All @@ -22,3 +27,20 @@
$map = 'strtoupper';
assertEquals(['FOO', 'BAR'], iterable_to_array(iterable_map($iterable, $map)));
});

it('maps iterable with object keys', function (): void {
foreach (iterable_map(iterableWithObjectKeys(), 'strtoupper') as $key => $item) {
assertInstanceOf(stdClass::class, $key);
assertSame('FOO', $item);

return;
}

Assert::fail('Did not iterate');
});

/** @return Generator<stdClass, string> */
function iterableWithObjectKeys(): Generator
{
yield new stdClass() => 'foo';
}