Skip to content

Commit

Permalink
Mappers should try to preserve keys
Browse files Browse the repository at this point in the history
Fixes #84

Tests that keys are preserved in fact
  • Loading branch information
sanmai committed Jul 15, 2020
1 parent 994ffe3 commit d2bfba5
Show file tree
Hide file tree
Showing 3 changed files with 67 additions and 5 deletions.
12 changes: 7 additions & 5 deletions src/Principal.php
Expand Up @@ -87,16 +87,18 @@ protected function map(callable $func)

private static function apply(iterable $previous, callable $func): iterable
{
foreach ($previous as $value) {
foreach ($previous as $key => $value) {
$result = $func($value);

// For generators we use keys they provide
if ($result instanceof \Generator) {
yield from $result;

continue;
}

// Case of a plain old mapping function
yield $result;
// In case of a plain old mapping function we use the original key
yield $key => $result;
}
}

Expand Down Expand Up @@ -131,8 +133,8 @@ protected function cast(callable $func)

private static function applyOnce(iterable $previous, callable $func): iterable
{
foreach ($previous as $value) {
yield $func($value);
foreach ($previous as $key => $value) {
yield $key => $func($value);
}
}

Expand Down
14 changes: 14 additions & 0 deletions tests/CastTest.php
Expand Up @@ -88,4 +88,18 @@ public function testCastUnpack(): void

$this->assertSame([0, 2, 6], $pipeline->toArray());
}

public function testCastPreservesKeys(): void
{
$this->assertSame([
'a' => 2,
'b' => 6,
], map(function () {
yield 'a' => 1;
yield 'b' => 2;
yield 'b' => 3;
})->cast(function (int $a) {
return $a * 2;
})->toArray(true));
}
}
46 changes: 46 additions & 0 deletions tests/MapTest.php
@@ -0,0 +1,46 @@
<?php
/**
* Copyright 2017, 2018 Alexey Kopytko <alexey@kopytko.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

declare(strict_types=1);

namespace Tests\Pipeline;

use PHPUnit\Framework\TestCase;
use function Pipeline\map;

/**
* @covers \Pipeline\Principal
* @covers \Pipeline\Standard
*
* @internal
*/
final class MapTest extends TestCase
{
public function testMapPreservesKeys(): void
{
$this->assertSame([
'a' => 2,
'b' => 6,
], map(function () {
yield 'a' => 1;
yield 'b' => 2;
yield 'b' => 3;
})->map(function (int $a) {
return $a * 2;
})->toArray(true));
}
}

0 comments on commit d2bfba5

Please sign in to comment.