Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 10 additions & 4 deletions src/gleam/float.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -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
///
Expand All @@ -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`:
Expand Down
14 changes: 10 additions & 4 deletions src/gleam/int.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -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
///
Expand All @@ -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.
Expand Down
2 changes: 2 additions & 0 deletions test/gleam/float_test.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down
3 changes: 2 additions & 1 deletion test/gleam/int_test.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down