Bläddra i källkod

LibJS: Allow conversion from Symbol to String via explicit String() call

https://tc39.es/ecma262/#sec-string-constructor-string-value has an
explicit special case for Symbols allowing this:

    If NewTarget is undefined and Type(value) is Symbol,
    return SymbolDescriptiveString(value).
Nico Weber 5 år sedan
förälder
incheckning
ebd510ef5e

+ 2 - 0
Libraries/LibJS/Runtime/StringConstructor.cpp

@@ -59,6 +59,8 @@ Value StringConstructor::call(Interpreter& interpreter)
 {
     if (!interpreter.argument_count())
         return js_string(interpreter, "");
+    if (interpreter.argument(0).is_symbol())
+        return js_string(interpreter, interpreter.argument(0).as_symbol().to_string());
     auto* string = interpreter.argument(0).to_primitive_string(interpreter);
     if (interpreter.exception())
         return {};

+ 4 - 2
Libraries/LibJS/Tests/builtins/Symbol/Symbol.prototype.toString.js

@@ -1,10 +1,12 @@
 describe("correct behavior", () => {
     test("basic functionality", () => {
         const s1 = Symbol("baz");
-        // const s2 = Symbol.for("qux");
+        const s2 = Symbol.for("qux");
 
+        // Explicit conversions to string are fine, but implicit toString via concatenation throws.
         expect(s1.toString()).toBe("Symbol(baz)");
-        // expect(s2.toString()).toBe("Symbol(qux)");
+        expect(String(s1)).toBe("Symbol(baz)");
+        expect(s2.toString()).toBe("Symbol(qux)");
     });
 });