Skip to content

Commit 17632c3

Browse files
committed
feat: Add Number::clamp()
1 parent 138cfec commit 17632c3

File tree

2 files changed

+62
-0
lines changed

2 files changed

+62
-0
lines changed

src/Number.php

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
<?php declare(strict_types=1);
2+
3+
namespace MLL\Utils;
4+
5+
final class Number
6+
{
7+
/**
8+
* Return number as long as its clamped between min and max.
9+
*
10+
* @see https://github.com/matthewbaggett/php-clamp/blob/master/src/Clamp.php
11+
* @see https://wiki.php.net/rfc/clamp
12+
*
13+
* @param float|int $min
14+
* @param float|int $max
15+
* @param float|int $current
16+
*
17+
* @return float|int
18+
*/
19+
public static function clamp($min, $max, $current)
20+
{
21+
return max($min, min($max, $current));
22+
}
23+
}

tests/Unit/NumberTest.php

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
<?php declare(strict_types=1);
2+
3+
namespace MLL\Utils\Tests\Unit;
4+
5+
use MLL\Utils\Number;
6+
use PHPUnit\Framework\TestCase;
7+
8+
final class NumberTest extends TestCase
9+
{
10+
/**
11+
* @dataProvider clampProvider
12+
*
13+
* @param float|int $min
14+
* @param float|int $max
15+
* @param float|int $current
16+
* @param float|int $expected
17+
*/
18+
public function testClamp($min, $max, $current, $expected): void
19+
{
20+
self::assertSame($expected, Number::clamp($min, $max, $current));
21+
}
22+
23+
/**
24+
* @return iterable<array{int|float, int|float, int|float, int|float}>
25+
*/
26+
public function clampProvider(): iterable
27+
{
28+
yield [1, 2, 3, 2];
29+
yield [1, 2, 0, 1];
30+
yield [-1, 2, 0, 0];
31+
yield [1, 3, 2, 2];
32+
yield [0.001, 0.003, 0.002, 0.002];
33+
yield [0.001, 0.003, 0.004, 0.003];
34+
yield [0.001, 0.003, 0.000, 0.001];
35+
yield [-1, +1, 0, 0];
36+
yield [-1, +1, 0.5, 0.5];
37+
yield [-1, +1, -2, -1];
38+
}
39+
}

0 commit comments

Comments
 (0)