From 60dd046d41e143bda03d736e4bf80aaeda284be0 Mon Sep 17 00:00:00 2001 From: Simon Podlipsky Date: Thu, 4 Feb 2021 11:15:45 +0100 Subject: [PATCH 1/2] add test --- tests/IterableMapTest.php | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/tests/IterableMapTest.php b/tests/IterableMapTest.php index c9b7c99..86b3207 100644 --- a/tests/IterableMapTest.php +++ b/tests/IterableMapTest.php @@ -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']; @@ -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 */ +function iterableWithObjectKeys(): Generator +{ + yield new stdClass() => 'foo'; +} From 7e8f271e4b8f89f104349f83ad22976ee6858a7d Mon Sep 17 00:00:00 2001 From: Simon Podlipsky Date: Thu, 4 Feb 2021 11:18:18 +0100 Subject: [PATCH 2/2] change implementation --- src/iterable-functions.php | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/src/iterable-functions.php b/src/iterable-functions.php index f9a698d..df51b9d 100644 --- a/src/iterable-functions.php +++ b/src/iterable-functions.php @@ -10,7 +10,6 @@ use Traversable; use function array_filter; -use function array_map; use function array_values; use function iterator_to_array; @@ -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); } /**