From 00fe7f82c09343a5b38e7bedf98a70c85c6e38f7 Mon Sep 17 00:00:00 2001 From: Linus Groh Date: Sat, 23 May 2020 15:02:14 +0100 Subject: [PATCH] LibJS: Treat NaN in Value::to_i32() as zero Let's treat it as zero like the ECMAScript spec does in toInteger(). That way we can use to_i32() and don't have to care about weird input input values where a number is expected, i.e. "foo".charAt() === "f" "foo".charAt("bar") === "f" "foo".charAt(0) === "f" --- Libraries/LibJS/Runtime/Value.cpp | 4 ++++ Libraries/LibJS/Tests/String.prototype.charAt.js | 5 +++++ 2 files changed, 9 insertions(+) diff --git a/Libraries/LibJS/Runtime/Value.cpp b/Libraries/LibJS/Runtime/Value.cpp index 80917df5d5..9f248829a3 100644 --- a/Libraries/LibJS/Runtime/Value.cpp +++ b/Libraries/LibJS/Runtime/Value.cpp @@ -274,6 +274,10 @@ i32 Value::to_i32(Interpreter& interpreter) const auto number = to_number(interpreter); if (interpreter.exception()) return 0; + if (number.is_nan()) + return 0; + // FIXME: What about infinity though - that's UB... + // Maybe NumericLimits::max() for +Infinity and NumericLimits::min() for -Infinity? return number.as_i32(); } diff --git a/Libraries/LibJS/Tests/String.prototype.charAt.js b/Libraries/LibJS/Tests/String.prototype.charAt.js index 9e9fbd96b4..234d388003 100644 --- a/Libraries/LibJS/Tests/String.prototype.charAt.js +++ b/Libraries/LibJS/Tests/String.prototype.charAt.js @@ -13,6 +13,11 @@ try { assert(s.charAt(5) === 'r'); assert(s.charAt(6) === ''); + assert(s.charAt() === 'f'); + assert(s.charAt(NaN) === 'f'); + assert(s.charAt("foo") === 'f'); + assert(s.charAt(undefined) === 'f'); + console.log("PASS"); } catch (e) { console.log("FAIL: " + e);