LibJS: Add spec comments and check for edge cases in Math.tanh

This commit is contained in:
davidot 2022-11-28 12:08:57 +01:00 committed by Andreas Kling
parent 8de8742b7c
commit bf1b2d63c6
Notes: sideshowbarker 2024-07-17 03:59:03 +09:00
2 changed files with 13 additions and 2 deletions

View file

@ -636,13 +636,22 @@ JS_DEFINE_NATIVE_FUNCTION(MathObject::cosh)
// 21.3.2.34 Math.tanh ( x ), https://tc39.es/ecma262/#sec-math.tanh
JS_DEFINE_NATIVE_FUNCTION(MathObject::tanh)
{
// 1. Let n be ? ToNumber(x).
auto number = TRY(vm.argument(0).to_number(vm));
if (number.is_nan())
return js_nan();
// 2. If n is NaN, n is +0𝔽, or n is -0𝔽, return n.
if (number.is_nan() || number.is_positive_zero() || number.is_negative_zero())
return number;
// 3. If n is +∞𝔽, return 1𝔽.
if (number.is_positive_infinity())
return Value(1);
// 4. If n is -∞𝔽, return -1𝔽.
if (number.is_negative_infinity())
return Value(-1);
// 5. Return an implementation-approximated Number value representing the result of the hyperbolic tangent of (n).
return Value(::tanh(number.as_double()));
}

View file

@ -5,4 +5,6 @@ test("basic functionality", () => {
expect(Math.tanh(Infinity)).toBe(1);
expect(Math.tanh(-Infinity)).toBe(-1);
expect(Math.tanh(1)).toBeCloseTo(0.7615941559557649);
expect(Math.tanh(NaN)).toBe(NaN);
expect(Math.tanh(-0.0)).toBe(-0.0);
});