LibJS: Add Math.{cos,sin,tan}()

This commit is contained in:
Linus Groh 2020-04-05 21:21:33 +01:00 committed by Andreas Kling
parent 04a36b247b
commit f5dacfbb5b
Notes: sideshowbarker 2024-07-19 07:52:00 +09:00
5 changed files with 79 additions and 0 deletions

View file

@ -43,6 +43,9 @@ MathObject::MathObject()
put_native_function("max", max, 2);
put_native_function("min", min, 2);
put_native_function("trunc", trunc, 1);
put_native_function("sin", sin, 1);
put_native_function("cos", cos, 1);
put_native_function("tan", tan, 1);
put("E", Value(M_E));
put("LN2", Value(M_LN2));
@ -152,4 +155,28 @@ Value MathObject::trunc(Interpreter& interpreter)
return MathObject::floor(interpreter);
}
Value MathObject::sin(Interpreter& interpreter)
{
auto number = interpreter.argument(0).to_number();
if (number.is_nan())
return js_nan();
return Value(::sin(number.as_double()));
}
Value MathObject::cos(Interpreter& interpreter)
{
auto number = interpreter.argument(0).to_number();
if (number.is_nan())
return js_nan();
return Value(::cos(number.as_double()));
}
Value MathObject::tan(Interpreter& interpreter)
{
auto number = interpreter.argument(0).to_number();
if (number.is_nan())
return js_nan();
return Value(::tan(number.as_double()));
}
}

View file

@ -47,6 +47,9 @@ private:
static Value max(Interpreter&);
static Value min(Interpreter&);
static Value trunc(Interpreter&);
static Value sin(Interpreter&);
static Value cos(Interpreter&);
static Value tan(Interpreter&);
};
}

View file

@ -0,0 +1,16 @@
try {
assert(Math.cos(0) === 1);
assert(Math.cos(null) === 1);
assert(Math.cos('') === 1);
assert(Math.cos([]) === 1);
assert(Math.cos(Math.PI) === -1);
assert(isNaN(Math.cos()));
assert(isNaN(Math.cos(undefined)));
assert(isNaN(Math.cos([1, 2, 3])));
assert(isNaN(Math.cos({})));
assert(isNaN(Math.cos("foo")));
console.log("PASS");
} catch (e) {
console.log("FAIL: " + e);
}

View file

@ -0,0 +1,17 @@
try {
assert(Math.sin(0) === 0);
assert(Math.sin(null) === 0);
assert(Math.sin('') === 0);
assert(Math.sin([]) === 0);
assert(Math.sin(Math.PI * 3 / 2) === -1);
assert(Math.sin(Math.PI / 2) === 1);
assert(isNaN(Math.sin()));
assert(isNaN(Math.sin(undefined)));
assert(isNaN(Math.sin([1, 2, 3])));
assert(isNaN(Math.sin({})));
assert(isNaN(Math.sin("foo")));
console.log("PASS");
} catch (e) {
console.log("FAIL: " + e);
}

View file

@ -0,0 +1,16 @@
try {
assert(Math.tan(0) === 0);
assert(Math.tan(null) === 0);
assert(Math.tan('') === 0);
assert(Math.tan([]) === 0);
assert(Math.ceil(Math.tan(Math.PI / 4)) === 1);
assert(isNaN(Math.tan()));
assert(isNaN(Math.tan(undefined)));
assert(isNaN(Math.tan([1, 2, 3])));
assert(isNaN(Math.tan({})));
assert(isNaN(Math.tan("foo")));
console.log("PASS");
} catch (e) {
console.log("FAIL: " + e);
}