diff --git a/vlib/math/math.v b/vlib/math/math.v index f0d4718c4c..366bf66c90 100644 --- a/vlib/math/math.v +++ b/vlib/math/math.v @@ -87,6 +87,18 @@ pub fn minmax(a f64, b f64) (f64, f64) { return b, a } +// clamp returns x constrained between a and b +[inline] +pub fn clamp(x f64, a f64, b f64) f64 { + if x < a { + return a + } + if x > b { + return b + } + return x +} + // sign returns the corresponding sign -1.0, 1.0 of the provided number. // if n is not a number, its sign is nan too. [inline] diff --git a/vlib/math/math_test.v b/vlib/math/math_test.v index 115a8c457e..14e6b3489f 100644 --- a/vlib/math/math_test.v +++ b/vlib/math/math_test.v @@ -435,6 +435,14 @@ fn test_min() { } } +fn test_clamp() { + assert clamp(2, 5, 10) == 5 + assert clamp(7, 5, 10) == 7 + assert clamp(15, 5, 10) == 10 + assert clamp(5, 5, 10) == 5 + assert clamp(10, 5, 10) == 10 +} + fn test_signi() { assert signi(inf(-1)) == -1 assert signi(-72234878292.4586129) == -1