diff options
-rw-r--r-- | CHANGELOG.md | 5 | ||||
-rw-r--r-- | src/gleam/float.gleam | 15 | ||||
-rw-r--r-- | src/gleam/int.gleam | 15 | ||||
-rw-r--r-- | test/gleam/float_test.gleam | 11 | ||||
-rw-r--r-- | test/gleam/int_test.gleam | 15 |
5 files changed, 61 insertions, 0 deletions
diff --git a/CHANGELOG.md b/CHANGELOG.md index 1bc6cc4..0d6e5b2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,10 @@ # Changelog +## Unreleased + +- The `int` module gains the `clamp` function. +- The `float` module gains the `clamp` function. + ## v0.13.0 - 2021-01-13 - The `int` module gains the `absolute_value`, `sum` and `product` functions. diff --git a/src/gleam/float.gleam b/src/gleam/float.gleam index f3944f3..a672eca 100644 --- a/src/gleam/float.gleam +++ b/src/gleam/float.gleam @@ -29,6 +29,21 @@ pub fn to_string(f: Float) -> String { |> string_builder.to_string } +/// Restrict a Float between a lower and upper bound +/// +/// ## Examples +/// +/// ``` +/// > clamp(1.2, min: 1.4, max: 1.6) +/// 1.4 +/// ``` +/// +pub fn clamp(n: Float, min min_bound: Float, max max_bound: Float) -> Float { + n + |> min(max_bound) + |> max(min_bound) +} + /// Compares two floats, returning an order. /// /// ## Examples diff --git a/src/gleam/int.gleam b/src/gleam/int.gleam index a4a956a..96b4405 100644 --- a/src/gleam/int.gleam +++ b/src/gleam/int.gleam @@ -75,6 +75,21 @@ pub external fn to_base_string(Int, Int) -> String = pub external fn to_float(a: Int) -> Float = "erlang" "float" +/// Restrict an Int between a lower and upper bound +/// +/// ## Examples +/// +/// ``` +/// > clamp(40, min: 50, max: 60) +/// 50 +/// ``` +/// +pub fn clamp(n: Int, min min_bound: Int, max max_bound: Int) -> Int { + n + |> min(max_bound) + |> max(min_bound) +} + /// Compares two ints, returning an order. /// /// ## Examples diff --git a/test/gleam/float_test.gleam b/test/gleam/float_test.gleam index 2b3334e..3e0e6f6 100644 --- a/test/gleam/float_test.gleam +++ b/test/gleam/float_test.gleam @@ -38,6 +38,17 @@ pub fn to_string_test() { |> should.equal("-8.1") } +pub fn clamp_test() { + float.clamp(1.4, min: 1.3, max: 1.5) + |> should.equal(1.4) + + float.clamp(1.2, min: 1.3, max: 1.5) + |> should.equal(1.3) + + float.clamp(1.6, min: 1.3, max: 1.5) + |> should.equal(1.5) +} + pub fn compare_test() { float.compare(0., 0.) |> should.equal(order.Eq) diff --git a/test/gleam/int_test.gleam b/test/gleam/int_test.gleam index 11906db..bec9624 100644 --- a/test/gleam/int_test.gleam +++ b/test/gleam/int_test.gleam @@ -12,6 +12,21 @@ pub fn absolute_value_test() { |> should.equal(123) } +pub fn clamp_test() { + int.clamp(40, min: 30, max: 50) + |> should.equal(40) + + int.clamp(20, min: 30, max: 50) + |> should.equal(30) + + int.clamp(60, min: 30, max: 50) + |> should.equal(50) + + // If the bounds are reversed we return the min + int.clamp(100, min: 50, max: 30) + |> should.equal(50) +} + pub fn to_string_test() { 123 |> int.to_string |