mirror of
https://github.com/RGBCube/serenity
synced 2025-07-23 03:07:39 +00:00
LibJS: Adding two values should convert them to primitives first
This commit is contained in:
parent
63499c2c9f
commit
fa30355194
3 changed files with 26 additions and 3 deletions
|
@ -100,6 +100,13 @@ bool Value::to_boolean() const
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Value Value::to_primitive(Interpreter&) const
|
||||||
|
{
|
||||||
|
if (is_object())
|
||||||
|
return as_object().to_primitive();
|
||||||
|
return *this;
|
||||||
|
}
|
||||||
|
|
||||||
Object* Value::to_object(Heap& heap) const
|
Object* Value::to_object(Heap& heap) const
|
||||||
{
|
{
|
||||||
if (is_object())
|
if (is_object())
|
||||||
|
@ -256,10 +263,13 @@ Value right_shift(Interpreter&, Value lhs, Value rhs)
|
||||||
|
|
||||||
Value add(Interpreter& interpreter, Value lhs, Value rhs)
|
Value add(Interpreter& interpreter, Value lhs, Value rhs)
|
||||||
{
|
{
|
||||||
if (lhs.is_string() || rhs.is_string())
|
auto lhs_primitive = lhs.to_primitive(interpreter);
|
||||||
return js_string(interpreter.heap(), String::format("%s%s", lhs.to_string().characters(), rhs.to_string().characters()));
|
auto rhs_primitive = rhs.to_primitive(interpreter);
|
||||||
|
|
||||||
return Value(lhs.to_number().as_double() + rhs.to_number().as_double());
|
if (lhs_primitive.is_string() || rhs_primitive.is_string())
|
||||||
|
return js_string(interpreter.heap(), String::format("%s%s", lhs_primitive.to_string().characters(), rhs_primitive.to_string().characters()));
|
||||||
|
|
||||||
|
return Value(lhs_primitive.to_number().as_double() + rhs_primitive.to_number().as_double());
|
||||||
}
|
}
|
||||||
|
|
||||||
Value sub(Interpreter&, Value lhs, Value rhs)
|
Value sub(Interpreter&, Value lhs, Value rhs)
|
||||||
|
|
|
@ -147,6 +147,7 @@ public:
|
||||||
Value to_number() const;
|
Value to_number() const;
|
||||||
i32 to_i32() const;
|
i32 to_i32() const;
|
||||||
double to_double() const;
|
double to_double() const;
|
||||||
|
Value to_primitive(Interpreter&) const;
|
||||||
|
|
||||||
Object* to_object(Heap&) const;
|
Object* to_object(Heap&) const;
|
||||||
|
|
||||||
|
|
12
Libraries/LibJS/Tests/add-values-to-primitive.js
Normal file
12
Libraries/LibJS/Tests/add-values-to-primitive.js
Normal file
|
@ -0,0 +1,12 @@
|
||||||
|
load("test-common.js");
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Note that these will give different results in the REPL due to parsing behavior.
|
||||||
|
assert([] + [] === "");
|
||||||
|
assert([] + {} === "[object Object]");
|
||||||
|
assert({} + {} === "[object Object][object Object]");
|
||||||
|
assert({} + [] === "[object Object]");
|
||||||
|
console.log("PASS");
|
||||||
|
} catch (e) {
|
||||||
|
console.log("FAIL: " + e);
|
||||||
|
}
|
Loading…
Add table
Add a link
Reference in a new issue