Skip to content

Commit

Permalink
Add ieee_float.clamp
Browse files Browse the repository at this point in the history
  • Loading branch information
richard-viney committed Jun 13, 2024
1 parent 98f7c94 commit fc18377
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 2 deletions.
16 changes: 14 additions & 2 deletions src/ieee_float.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,8 @@ pub fn is_nan(f: IEEEFloat) -> Bool {
f == NaN
}

/// Converts the `IEEEFloat` to a finite value of the native `Float` type. If
/// the IEEE float is infinite or `NaN` then `fallback` is returned.
/// Converts an `IEEEFloat` to a finite value of the native `Float` type. If
/// the `IEEEFloat` is infinite or `NaN` then `fallback` is returned.
///
@external(javascript, "./ieee_float_js.mjs", "to_finite")
pub fn to_finite(f: IEEEFloat, fallback: Float) -> Float {
Expand Down Expand Up @@ -284,6 +284,18 @@ pub fn ceiling(f: IEEEFloat) -> IEEEFloat {
}
}

/// Restricts an `IEEEFloat` between a lower and upper bound.
///
pub fn clamp(
f: IEEEFloat,
min min_bound: IEEEFloat,
max max_bound: IEEEFloat,
) -> IEEEFloat {
f
|> min(max_bound)
|> max(min_bound)
}

/// Compares two `IEEEFloats`, returning an `Order`: `Lt` for lower than, `Eq`
/// for equals, or `Gt` for greater than. If either value is `NaN` then
/// `Error(Nil)` is returned.
Expand Down
33 changes: 33 additions & 0 deletions test/ieee_float_test.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -327,6 +327,39 @@ pub fn ceiling_test() {
|> expect.to_equal(negative_infinity())
}

pub fn clamp_test() {
ieee_float.clamp(finite(1.4), min: finite(1.3), max: finite(1.5))
|> expect.to_equal(finite(1.4))

ieee_float.clamp(finite(1.2), min: finite(1.3), max: finite(1.5))
|> expect.to_equal(finite(1.3))

ieee_float.clamp(finite(1.6), min: finite(1.3), max: finite(1.5))
|> expect.to_equal(finite(1.5))

ieee_float.clamp(
finite(1.6),
min: positive_infinity(),
max: positive_infinity(),
)
|> expect.to_equal(positive_infinity())

ieee_float.clamp(
finite(1.6),
min: negative_infinity(),
max: negative_infinity(),
)
|> expect.to_equal(negative_infinity())

ieee_float.clamp(nan(), min: finite(0.0), max: finite(0.0))
|> ieee_float.is_nan
|> expect.to_be_true

ieee_float.clamp(finite(0.0), min: nan(), max: finite(100.0))
|> ieee_float.is_nan
|> expect.to_be_true
}

pub fn compare_test() {
ieee_float.compare(finite(1.0), finite(1.0))
|> expect.to_equal(Ok(order.Eq))
Expand Down

0 comments on commit fc18377

Please sign in to comment.