diff --git a/src/gleam/float.gleam b/src/gleam/float.gleam index 83bfa6e6..dc563747 100644 --- a/src/gleam/float.gleam +++ b/src/gleam/float.gleam @@ -63,7 +63,7 @@ pub fn parse(string: String) -> Result(Float, Nil) @external(javascript, "../gleam_stdlib.mjs", "float_to_string") pub fn to_string(x: Float) -> String -/// Restricts a `Float` between a lower and upper bound. +/// Restricts a `Float` between two bounds. /// /// ## Examples /// @@ -72,10 +72,16 @@ pub fn to_string(x: Float) -> String /// // -> 1.4 /// ``` /// +/// ```gleam +/// clamp(1.2, min: 1.4, max: 0.6) +/// // -> 1.2 +/// ``` +/// pub fn clamp(x: Float, min min_bound: Float, max max_bound: Float) -> Float { - x - |> min(max_bound) - |> max(min_bound) + case min_bound >=. max_bound { + True -> x |> min(min_bound) |> max(max_bound) + False -> x |> min(max_bound) |> max(min_bound) + } } /// Compares two `Float`s, returning an `Order`: diff --git a/src/gleam/int.gleam b/src/gleam/int.gleam index 060ea890..4e00fc25 100644 --- a/src/gleam/int.gleam +++ b/src/gleam/int.gleam @@ -277,7 +277,7 @@ pub fn to_base36(x: Int) -> String { @external(javascript, "../gleam_stdlib.mjs", "identity") pub fn to_float(x: Int) -> Float -/// Restricts an int between a lower and upper bound. +/// Restricts an int between two bounds. /// /// ## Examples /// @@ -286,10 +286,16 @@ pub fn to_float(x: Int) -> Float /// // -> 50 /// ``` /// +/// ```gleam +/// clamp(40, min: 50, max: 30) +/// // -> 40 +/// ``` +/// pub fn clamp(x: Int, min min_bound: Int, max max_bound: Int) -> Int { - x - |> min(max_bound) - |> max(min_bound) + case min_bound >= max_bound { + True -> x |> min(min_bound) |> max(max_bound) + False -> x |> min(max_bound) |> max(min_bound) + } } /// Compares two ints, returning an order. diff --git a/test/gleam/float_test.gleam b/test/gleam/float_test.gleam index d4eb0a93..f5c96f7e 100644 --- a/test/gleam/float_test.gleam +++ b/test/gleam/float_test.gleam @@ -66,6 +66,8 @@ pub fn clamp_test() { assert float.clamp(1.2, min: 1.3, max: 1.5) == 1.3 assert float.clamp(1.6, min: 1.3, max: 1.5) == 1.5 + + assert float.clamp(1.2, min: 1.4, max: 0.6) == 1.2 } pub fn compare_test() { diff --git a/test/gleam/int_test.gleam b/test/gleam/int_test.gleam index 26ae9ec0..db5a3aa5 100644 --- a/test/gleam/int_test.gleam +++ b/test/gleam/int_test.gleam @@ -15,8 +15,9 @@ pub fn clamp_test() { assert int.clamp(60, min: 30, max: 50) == 50 - // If the bounds are reversed we return the min assert int.clamp(100, min: 50, max: 30) == 50 + + assert int.clamp(40, min: 50, max: 30) == 40 } pub fn to_string_test() {