Skip to content

Commit

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

/// Get an approximation of the square root of the sum of squares of all arguments.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-math.hypot
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/hypot
pub(crate) fn hypot(_: &Value, args: &[Value], _: &mut Interpreter) -> ResultValue {
Ok(args.iter().fold(0f64, |x, v| f64::from(v).hypot(x)).into())
}

/// Get the natural logarithm of a number.
///
/// More information:
Expand Down Expand Up @@ -546,6 +558,7 @@ impl Math {
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::hypot, "hypot", &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 @@ -360,6 +360,36 @@ fn fround() {
assert_eq!(f.to_number(), -5.050_000_190_734_863);
}

#[test]
fn hypot() {
let realm = Realm::create();
let mut engine = Interpreter::new(realm);
let init = r#"
var a = Math.hypot();
var b = Math.hypot(3, 4);
var c = Math.hypot(5, 12);
var d = Math.hypot(3, 4, -5);
var e = Math.hypot(4, [5], 6);
var f = Math.hypot(3, Infinity);
"#;

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

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

assert_eq!(a.to_number(), 0f64);
assert_eq!(b.to_number(), 5f64);
assert_eq!(c.to_number(), 13f64);
assert_eq!(d.to_number(), 7.071_067_811_865_475_5);
assert_eq!(e, String::from("NaN"));
assert_eq!(f, String::from("Infinity"));
}

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

0 comments on commit c061b69

Please sign in to comment.