Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Math] clamp function #111

Merged
merged 1 commit into from
Jan 18, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
],
];
}
}