From 42eac3b7d33ab3f8f1d42b6a11cd61587e75f775 Mon Sep 17 00:00:00 2001 From: Linus Groh Date: Sat, 10 Dec 2022 00:01:45 +0000 Subject: [PATCH] LibJS: Add spec comments to Value::to_u16() --- Userland/Libraries/LibJS/Runtime/Value.cpp | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/Userland/Libraries/LibJS/Runtime/Value.cpp b/Userland/Libraries/LibJS/Runtime/Value.cpp index 2078895f6c..2b336de147 100644 --- a/Userland/Libraries/LibJS/Runtime/Value.cpp +++ b/Userland/Libraries/LibJS/Runtime/Value.cpp @@ -959,15 +959,24 @@ ThrowCompletionOr Value::to_i16(VM& vm) const // 7.1.9 ToUint16 ( argument ), https://tc39.es/ecma262/#sec-touint16 ThrowCompletionOr Value::to_u16(VM& vm) const { - double value = TRY(to_number(vm)).as_double(); - if (!isfinite(value) || value == 0) + // 1. Let number be ? ToNumber(argument). + double number = TRY(to_number(vm)).as_double(); + + // 2. If number is not finite or number is either +0𝔽 or -0𝔽, return +0𝔽. + if (!isfinite(number) || number == 0) return 0; - auto int_val = floor(fabs(value)); - if (signbit(value)) + + // 3. Let int be the mathematical value whose sign is the sign of number and whose magnitude is floor(abs(ℝ(number))). + auto int_val = floor(fabs(number)); + if (signbit(number)) int_val = -int_val; + + // 4. Let int16bit be int modulo 2^16. auto int16bit = fmod(int_val, NumericLimits::max() + 1.0); if (int16bit < 0) int16bit += NumericLimits::max() + 1.0; + + // 5. Return 𝔽(int16bit). return static_cast(int16bit); }