1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-06-01 08:28:11 +00:00

LibJS: Add Math.sqrt()

This commit is contained in:
Andreas Kling 2020-04-04 22:44:48 +02:00
parent d155491122
commit d4dfe7e525
3 changed files with 23 additions and 3 deletions

View file

@ -28,7 +28,7 @@
#include <AK/Function.h>
#include <LibJS/Interpreter.h>
#include <LibJS/Runtime/MathObject.h>
#include <LibM/math.h>
#include <math.h>
namespace JS {
@ -36,6 +36,7 @@ MathObject::MathObject()
{
put_native_function("abs", abs, 1);
put_native_function("random", random);
put_native_function("sqrt", sqrt);
put("E", Value(M_E));
put("LN2", Value(M_LN2));
@ -43,8 +44,8 @@ MathObject::MathObject()
put("LOG2E", Value(log2(M_E)));
put("LOG10E", Value(log10(M_E)));
put("PI", Value(M_PI));
put("SQRT1_2", Value(sqrt(1 / 2)));
put("SQRT2", Value(sqrt(2)));
put("SQRT1_2", Value(::sqrt(1 / 2)));
put("SQRT2", Value(::sqrt(2)));
}
MathObject::~MathObject()
@ -72,4 +73,15 @@ Value MathObject::random(Interpreter&)
return Value(r);
}
Value MathObject::sqrt(Interpreter& interpreter)
{
if (!interpreter.argument_count())
return js_nan();
auto number = interpreter.argument(0).to_number();
if (number.is_nan())
return js_nan();
return Value(::sqrt(number.as_double()));
}
}

View file

@ -40,6 +40,7 @@ private:
static Value abs(Interpreter&);
static Value random(Interpreter&);
static Value sqrt(Interpreter&);
};
}

View file

@ -0,0 +1,7 @@
function assert(x) { if (!x) throw 1; }
try {
assert(Math.sqrt(9) === 3);
console.log("PASS");
} catch {
}