Skip to content

Commit

Permalink
[boa-dev#524] add implementation for Math.fround()
Browse files Browse the repository at this point in the history
  • Loading branch information
mr-rodgers committed Jun 25, 2020
1 parent 419f409 commit 509a587
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
16 changes: 16 additions & 0 deletions boa/src/builtins/math/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,21 @@ impl Math {
.into())
}

/// Get the nearest 32-bit single precision float representation of a number.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-math.fround
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/fround
pub(crate) fn fround(_: &Value, args: &[Value], _: &mut Interpreter) -> ResultValue {
Ok(args
.get(0)
.map_or(f64::NAN, |x| (f64::from(x) as f32) as f64)
.into())
}

/// Get the natural logarithm of a number.
///
/// More information:
Expand Down Expand Up @@ -530,6 +545,7 @@ impl Math {
make_builtin_fn(Self::exp, "exp", &math, 1);
make_builtin_fn(Self::expm1, "expm1", &math, 1);
make_builtin_fn(Self::floor, "floor", &math, 1);
make_builtin_fn(Self::fround, "fround", &math, 1);
make_builtin_fn(Self::log, "log", &math, 1);
make_builtin_fn(Self::log10, "log10", &math, 1);
make_builtin_fn(Self::log2, "log2", &math, 1);
Expand Down
30 changes: 30 additions & 0 deletions boa/src/builtins/math/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -330,6 +330,36 @@ fn floor() {
assert_eq!(c.to_number(), 3_f64);
}

#[test]
fn fround() {
let realm = Realm::create();
let mut engine = Interpreter::new(realm);
let init = r#"
var a = Math.fround(NaN);
var b = Math.fround(Infinity);
var c = Math.fround(5);
var d = Math.fround(5.5);
var e = Math.fround(5.05);
var f = Math.fround(-5.05);
"#;

eprintln!("{}", forward(&mut engine, init));

let a = forward(&mut engine, "a");
let b = forward(&mut engine, "b");
let c = forward_val(&mut engine, "c").unwrap();
let d = forward_val(&mut engine, "d").unwrap();
let e = forward_val(&mut engine, "e").unwrap();
let f = forward_val(&mut engine, "f").unwrap();

assert_eq!(a, String::from("NaN"));
assert_eq!(b, String::from("Infinity"));
assert_eq!(c.to_number(), 5f64);
assert_eq!(d.to_number(), 5.5f64);
assert_eq!(e.to_number(), 5.050_000_190_734_863);
assert_eq!(f.to_number(), -5.050_000_190_734_863);
}

#[test]
fn log() {
let realm = Realm::create();
Expand Down

0 comments on commit 509a587

Please sign in to comment.