From c507da9d6cd49307264c6b66de09fc247f88d738 Mon Sep 17 00:00:00 2001 From: Toon Verwerft Date: Mon, 18 Jan 2021 08:18:55 +0100 Subject: [PATCH] Add Math\clamp() function --- src/Psl/Internal/Loader.php | 1 + src/Psl/Math/clamp.php | 36 +++++++++++++++++ tests/Psl/Math/ClampTest.php | 76 ++++++++++++++++++++++++++++++++++++ 3 files changed, 113 insertions(+) create mode 100644 src/Psl/Math/clamp.php create mode 100644 tests/Psl/Math/ClampTest.php diff --git a/src/Psl/Internal/Loader.php b/src/Psl/Internal/Loader.php index 1849964aa..1ead57d75 100644 --- a/src/Psl/Internal/Loader.php +++ b/src/Psl/Internal/Loader.php @@ -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', diff --git a/src/Psl/Math/clamp.php b/src/Psl/Math/clamp.php new file mode 100644 index 000000000..6ed73eb1d --- /dev/null +++ b/src/Psl/Math/clamp.php @@ -0,0 +1,36 @@ + $max) { + return $max; + } + + return $number; +} diff --git a/tests/Psl/Math/ClampTest.php b/tests/Psl/Math/ClampTest.php new file mode 100644 index 000000000..a4dcc7263 --- /dev/null +++ b/tests/Psl/Math/ClampTest.php @@ -0,0 +1,76 @@ +expectException(Exception\InvariantViolationException::class); + $this->expectExceptionMessage('Expected 20 to be lower or equal to 10.'); + + 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 + ], + ]; + } +}