Skip to content

Commit

Permalink
Change ieee_float.to_finite to return a Result
Browse files Browse the repository at this point in the history
  • Loading branch information
richard-viney committed Jun 14, 2024
1 parent f2e0921 commit 64b2541
Show file tree
Hide file tree
Showing 4 changed files with 17 additions and 17 deletions.
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,9 @@ pub fn main() {
let assert True = ieee_float.is_nan(nan)
// Convert to a finite value of type `Float`. If the IEEE float is not
// finite then the fallback value is returned.
let assert 1.0 = ieee_float.to_finite(one, 5.0)
let assert 5.0 = ieee_float.to_finite(positive_inf, 5.0)
// finite then an error is returned.
let assert Ok(1.0) = ieee_float.to_finite(one)
let assert Error(Nil) = ieee_float.to_finite(positive_inf)
// Convert a value to raw bytes
let assert <<0x3F, 0x80, 0x00, 0x00>> = ieee_float.to_bytes_32_be(one)
Expand Down
8 changes: 4 additions & 4 deletions src/ieee_float.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -71,13 +71,13 @@ pub fn is_nan(f: IEEEFloat) -> Bool {
}

/// Converts an `IEEEFloat` to the native `Float` type. If the `IEEEFloat` is
/// infinite or `NaN` then `fallback` is returned.
/// infinite or `NaN` then `Error(Nil)` is returned.
///
@external(javascript, "./ieee_float_js.mjs", "to_finite")
pub fn to_finite(f: IEEEFloat, fallback: Float) -> Float {
pub fn to_finite(f: IEEEFloat) -> Result(Float, Nil) {
case f {
Finite(value) -> value
_ -> fallback
Finite(value) -> Ok(value)
_ -> Error(Nil)
}
}

Expand Down
4 changes: 2 additions & 2 deletions src/ieee_float_js.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,8 @@ export function is_nan(f) {
return Number.isNaN(f);
}

export function to_finite(f, fallback) {
return Number.isFinite(f) ? f : fallback;
export function to_finite(f) {
return Number.isFinite(f) ? new Ok(f) : new Error(Nil);
}

export function to_string(f) {
Expand Down
16 changes: 8 additions & 8 deletions test/ieee_float_test.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -47,20 +47,20 @@ pub fn nan_test() {

pub fn to_finite_test() {
finite(1.0)
|> ieee_float.to_finite(2.0)
|> expect.to_equal(1.0)
|> ieee_float.to_finite
|> expect.to_equal(Ok(1.0))

positive_infinity()
|> ieee_float.to_finite(2.0)
|> expect.to_equal(2.0)
|> ieee_float.to_finite
|> expect.to_equal(Error(Nil))

negative_infinity()
|> ieee_float.to_finite(2.0)
|> expect.to_equal(2.0)
|> ieee_float.to_finite
|> expect.to_equal(Error(Nil))

nan()
|> ieee_float.to_finite(2.0)
|> expect.to_equal(2.0)
|> ieee_float.to_finite
|> expect.to_equal(Error(Nil))
}

pub fn to_string_test() {
Expand Down

0 comments on commit 64b2541

Please sign in to comment.