diff --git a/Userland/Libraries/LibJS/Runtime/Value.cpp b/Userland/Libraries/LibJS/Runtime/Value.cpp index 08eb5c96da..d658805f48 100644 --- a/Userland/Libraries/LibJS/Runtime/Value.cpp +++ b/Userland/Libraries/LibJS/Runtime/Value.cpp @@ -1033,21 +1033,39 @@ ThrowCompletionOr Value::to_u8(VM& vm) const // 7.1.12 ToUint8Clamp ( argument ), https://tc39.es/ecma262/#sec-touint8clamp ThrowCompletionOr Value::to_u8_clamp(VM& vm) const { + // 1. Let number be ? ToNumber(argument). auto number = TRY(to_number(vm)); + + // 2. If number is NaN, return +0𝔽. if (number.is_nan()) return 0; + double value = number.as_double(); + + // 3. If ℝ(number) ≤ 0, return +0𝔽. if (value <= 0.0) return 0; + + // 4. If ℝ(number) ≥ 255, return 255𝔽. if (value >= 255.0) return 255; + + // 5. Let f be floor(ℝ(number)). auto int_val = floor(value); + + // 6. If f + 0.5 < ℝ(number), return 𝔽(f + 1). if (int_val + 0.5 < value) return static_cast(int_val + 1.0); + + // 7. If ℝ(number) < f + 0.5, return 𝔽(f). if (value < int_val + 0.5) return static_cast(int_val); + + // 8. If f is odd, return 𝔽(f + 1). if (fmod(int_val, 2.0) == 1.0) return static_cast(int_val + 1.0); + + // 9. Return 𝔽(f). return static_cast(int_val); }