Browse Source

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

davidot 2 years ago
parent
commit
eda90b54d4

+ 20 - 3
Userland/Libraries/LibJS/Runtime/MathObject.cpp

@@ -548,10 +548,27 @@ JS_DEFINE_NATIVE_FUNCTION(MathObject::log)
 // 21.3.2.23 Math.log2 ( x ), https://tc39.es/ecma262/#sec-math.log2
 JS_DEFINE_NATIVE_FUNCTION(MathObject::log2)
 {
-    auto value = TRY(vm.argument(0).to_number(vm)).as_double();
-    if (value < 0)
+    // 1. Let n be ? ToNumber(x).
+    auto number = TRY(vm.argument(0).to_number(vm));
+
+    // 2. If n is NaN or n is +∞𝔽, return n.
+    if (number.is_nan() || number.is_positive_infinity())
+        return number;
+
+    // 3. If n is 1𝔽, return +0𝔽.
+    if (number.as_double() == 1.)
+        return Value(0);
+
+    // 4. If n is +0𝔽 or n is -0𝔽, return -∞𝔽.
+    if (number.is_positive_zero() || number.is_negative_zero())
+        return js_negative_infinity();
+
+    // 5. If n < -0𝔽, return NaN.
+    if (number.as_double() < -0.)
         return js_nan();
-    return Value(::log2(value));
+
+    // 6. Return an implementation-approximated Number value representing the result of the base 2 logarithm of ℝ(n).
+    return Value(::log2(number.as_double()));
 }
 
 // 21.3.2.22 Math.log10 ( x ), https://tc39.es/ecma262/#sec-math.log10

+ 3 - 0
Userland/Libraries/LibJS/Tests/builtins/Math/Math.log2.js

@@ -7,4 +7,7 @@ test("basic functionality", () => {
     expect(Math.log2(0)).toBe(-Infinity);
     expect(Math.log2(-2)).toBe(NaN);
     expect(Math.log2(1024)).toBe(10);
+    expect(Math.log2(NaN)).toBe(NaN);
+    expect(Math.log2(Number.POSITIVE_INFINITY)).toBe(Number.POSITIVE_INFINITY);
+    expect(Math.log2(-0.0)).toBe(Number.NEGATIVE_INFINITY);
 });