Skip to content

Commit

Permalink
Add Math\clamp() function (#111)
Browse files Browse the repository at this point in the history
  • Loading branch information
veewee authored Jan 18, 2021
1 parent 748ef0f commit 75484cc
Show file tree
Hide file tree
Showing 3 changed files with 113 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/Psl/Internal/Loader.php
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,7 @@ final class Loader
'Psl\Math\abs',
'Psl\Math\base_convert',
'Psl\Math\ceil',
'Psl\Math\clamp',
'Psl\Math\cos',
'Psl\Math\div',
'Psl\Math\exp',
Expand Down
36 changes: 36 additions & 0 deletions src/Psl/Math/clamp.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<?php

declare(strict_types=1);

namespace Psl\Math;

use Psl;

/**
* Returns a number whose value is limited to the given range.
*
* @template T of float|int
*
* @param T $number
* @param T $min
* @param T $max
*
* @return T
* @throws Psl\Exception\InvariantViolationException If min is bigger than max
*
* @psalm-pure
*/
function clamp($number, $min, $max)
{
Psl\invariant($min <= $max, 'Expected $min to be lower or equal to $max.');

if ($number < $min) {
return $min;
}

if ($number > $max) {
return $max;
}

return $number;
}
76 changes: 76 additions & 0 deletions tests/Psl/Math/ClampTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
<?php

declare(strict_types=1);

namespace Psl\Tests\Math;

use PHPUnit\Framework\TestCase;
use Psl\Exception;
use Psl\Math;

final class ClampTest extends TestCase
{
/**
* @dataProvider provideData
*/
public function testClamp($expected, $number, $min, $max): void
{
static::assertSame($expected, Math\clamp($number, $min, $max));
}

public function testInvalidMinMax(): void
{
$this->expectException(Exception\InvariantViolationException::class);
$this->expectExceptionMessage('Expected $min to be lower or equal to $max.');

Math\clamp(10, 20, 10);
}

public function provideData(): array
{
return [
[
'expected' => 10,
'number' => 10,
'min' => 2,
'max' => 20
],
[
'expected' => 10,
'number' => 20,
'min' => 1,
'max' => 10
],
[
'expected' => 10,
'number' => 5,
'min' => 10,
'max' => 20
],
[
'expected' => 10,
'number' => 10,
'min' => 10,
'max' => 20
],
[
'expected' => 10,
'number' => 10,
'min' => 1,
'max' => 10
],
[
'expected' => 10,
'number' => 20,
'min' => 10,
'max' => 10
],
[
'expected' => 10.0,
'number' => 10.0,
'min' => 2.0,
'max' => 20.0
],
];
}
}

0 comments on commit 75484cc

Please sign in to comment.