Skip to content

Commit

Permalink
Implement LambdaTransformer (#381)
Browse files Browse the repository at this point in the history
  • Loading branch information
akondas authored May 13, 2019
1 parent c1c9873 commit ff118eb
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 0 deletions.
30 changes: 30 additions & 0 deletions src/Preprocessing/LambdaTransformer.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?php

declare(strict_types=1);

namespace Phpml\Preprocessing;

final class LambdaTransformer implements Preprocessor
{
/**
* @var callable
*/
private $lambda;

public function __construct(callable $lambda)
{
$this->lambda = $lambda;
}

public function fit(array $samples, ?array $targets = null): void
{
// nothing to do
}

public function transform(array &$samples, ?array &$targets = null): void
{
foreach ($samples as &$sample) {
$sample = call_user_func($this->lambda, $sample);
}
}
}
28 changes: 28 additions & 0 deletions tests/Preprocessing/LambdaTransformerTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

declare(strict_types=1);

namespace Phpml\Tests\Preprocessing;

use Phpml\Preprocessing\LambdaTransformer;
use PHPUnit\Framework\TestCase;

final class LambdaTransformerTest extends TestCase
{
public function testLambdaSampleTransformation(): void
{
$transformer = new LambdaTransformer(static function ($sample): int {
return $sample[0] + $sample[1];
});

$samples = [
[1, 2],
[3, 4],
[5, 6],
];

$transformer->transform($samples);

self::assertEquals([3, 7, 11], $samples);
}
}

0 comments on commit ff118eb

Please sign in to comment.