[Fun] add when function (#85)

This commit is contained in:
Toon Verwerft 2020-10-09 14:54:24 +02:00 committed by GitHub
parent 2336e5624e
commit d1c54e429e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 70 additions and 0 deletions

36
src/Psl/Fun/when.php Normal file
View File

@ -0,0 +1,36 @@
<?php
declare(strict_types=1);
namespace Psl\Fun;
/**
* Creates a callback that can run a left or right function based on a condition.
*
* Example:
*
* $greet = Fun\when(
* static fn(string $name): bool => $name === 'Jos',
* static fn(string $name): string => 'Bonjour Jos!',
* static fn(string $name): string => 'Hello ' . $name . '!'
* );
*
* $greet('World')
* => Str('Hello World!');
*
* $greet('Jos')
* => Str('Bonjour Jos!');
*
* @template Ti
* @template To
*
* @psalm-param (callable(Ti): bool) $condition
* @psalm-param (callable(Ti): To) $then
* @psalm-param (callable(Ti): To) $else
*
* @psalm-return (callable(Ti): To)
*/
function when(callable $condition, callable $then, callable $else): callable
{
return fn ($value) => $condition($value) ? $then($value) : $else($value);
}

View File

@ -99,6 +99,7 @@ final class Loader
'Psl\Fun\passthrough',
'Psl\Fun\pipe',
'Psl\Fun\rethrow',
'Psl\Fun\when',
'Psl\Internal\boolean',
'Psl\Internal\type',
'Psl\Internal\validate_offset',

View File

@ -0,0 +1,33 @@
<?php
declare(strict_types=1);
namespace Psl\Tests\Fun;
use PHPUnit\Framework\TestCase;
use Psl\Fun;
final class WhenTest extends TestCase
{
public function testItRunsLeftFunction(): void
{
$greet = Fun\when(
static fn(string $name): bool => $name === 'Jos',
static fn(string $name): string => 'Bonjour ' . $name . '!',
static fn(string $name): string => 'Hello ' . $name . '!'
);
self::assertSame('Bonjour Jos!', $greet('Jos'));
}
public function testItRunsRightfunction(): void
{
$greet = Fun\when(
static fn(string $name): bool => $name === 'Jos',
static fn(string $name): string => 'Bonjour ' . $name . '!',
static fn(string $name): string => 'Hello ' . $name . '!'
);
self::assertSame('Hello World!', $greet('World'));
}
}