Skip to content

Commit 08f6be1

Browse files
committed
LibJS: Add spec comments to unary_minus()
1 parent 4458b7b commit 08f6be1

File tree

1 file changed

+30
-6
lines changed

1 file changed

+30
-6
lines changed

Userland/Libraries/LibJS/Runtime/Value.cpp

Lines changed: 30 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1456,17 +1456,41 @@ ThrowCompletionOr<Value> unary_plus(VM& vm, Value lhs)
14561456
}
14571457

14581458
// 13.5.5 Unary - Operator, https://tc39.es/ecma262/#sec-unary-minus-operator
1459+
// UnaryExpression : - UnaryExpression
14591460
ThrowCompletionOr<Value> unary_minus(VM& vm, Value lhs)
14601461
{
1461-
auto lhs_numeric = TRY(lhs.to_numeric(vm));
1462-
if (lhs_numeric.is_number()) {
1463-
if (lhs_numeric.is_nan())
1462+
// 1. Let expr be ? Evaluation of UnaryExpression.
1463+
// NOTE: This is handled in the AST or Bytecode interpreter.
1464+
1465+
// 2. Let oldValue be ? ToNumeric(? GetValue(expr)).
1466+
auto old_value = TRY(lhs.to_numeric(vm));
1467+
1468+
// 3. If oldValue is a Number, then
1469+
if (old_value.is_number()) {
1470+
// a. Return Number::unaryMinus(oldValue).
1471+
1472+
// 6.1.6.1.1 Number::unaryMinus ( x ), https://tc39.es/ecma262/#sec-numeric-types-number-unaryMinus
1473+
// 1. If x is NaN, return NaN.
1474+
if (old_value.is_nan())
14641475
return js_nan();
1465-
return Value(-lhs_numeric.as_double());
1476+
1477+
// 2. Return the result of negating x; that is, compute a Number with the same magnitude but opposite sign.
1478+
return Value(-old_value.as_double());
14661479
}
1467-
if (lhs_numeric.as_bigint().big_integer() == BIGINT_ZERO)
1480+
1481+
// 4. Else,
1482+
// a. Assert: oldValue is a BigInt.
1483+
VERIFY(old_value.is_bigint());
1484+
1485+
// b. Return BigInt::unaryMinus(oldValue).
1486+
1487+
// 6.1.6.2.1 BigInt::unaryMinus ( x ), https://tc39.es/ecma262/#sec-numeric-types-bigint-unaryMinus
1488+
// 1. If x is 0ℤ, return 0ℤ.
1489+
if (old_value.as_bigint().big_integer() == BIGINT_ZERO)
14681490
return BigInt::create(vm, BIGINT_ZERO);
1469-
auto big_integer_negated = lhs_numeric.as_bigint().big_integer();
1491+
1492+
// 2. Return the BigInt value that represents the negation of ℝ(x).
1493+
auto big_integer_negated = old_value.as_bigint().big_integer();
14701494
big_integer_negated.negate();
14711495
return BigInt::create(vm, big_integer_negated);
14721496
}

0 commit comments

Comments
 (0)