Parcourir la source

LibJS: Implement Temporal.TimeZone.prototype.toString()

Linus Groh il y a 4 ans
Parent
commit
8d00504ff2

+ 30 - 0
Userland/Libraries/LibJS/Runtime/Temporal/TimeZonePrototype.cpp

@@ -5,6 +5,7 @@
  */
 
 #include <LibJS/Runtime/GlobalObject.h>
+#include <LibJS/Runtime/Temporal/TimeZone.h>
 #include <LibJS/Runtime/Temporal/TimeZonePrototype.h>
 
 namespace JS::Temporal {
@@ -21,8 +22,37 @@ void TimeZonePrototype::initialize(GlobalObject& global_object)
 
     auto& vm = this->vm();
 
+    u8 attr = Attribute::Writable | Attribute::Configurable;
+    define_native_function(vm.names.toString, to_string, 0, attr);
+
     // 11.4.2 Temporal.TimeZone.prototype[ @@toStringTag ], https://tc39.es/proposal-temporal/#sec-temporal.timezone.prototype-@@tostringtag
     define_direct_property(*vm.well_known_symbol_to_string_tag(), js_string(vm.heap(), "Temporal.TimeZone"), Attribute::Configurable);
 }
 
+static TimeZone* typed_this(GlobalObject& global_object)
+{
+    auto& vm = global_object.vm();
+    auto* this_object = vm.this_value(global_object).to_object(global_object);
+    if (!this_object)
+        return {};
+    if (!is<TimeZone>(this_object)) {
+        vm.throw_exception<TypeError>(global_object, ErrorType::NotA, "Temporal.TimeZone");
+        return {};
+    }
+    return static_cast<TimeZone*>(this_object);
+}
+
+// 11.4.11 Temporal.TimeZone.prototype.toString ( ), https://tc39.es/proposal-temporal/#sec-temporal.timezone.prototype.tostring
+JS_DEFINE_NATIVE_FUNCTION(TimeZonePrototype::to_string)
+{
+    // 1. Let timeZone be the this value.
+    // 2. Perform ? RequireInternalSlot(timeZone, [[InitializedTemporalTimeZone]]).
+    auto* time_zone = typed_this(global_object);
+    if (vm.exception())
+        return {};
+
+    // 3. Return timeZone.[[Identifier]].
+    return js_string(vm, time_zone->identifier());
+}
+
 }

+ 3 - 0
Userland/Libraries/LibJS/Runtime/Temporal/TimeZonePrototype.h

@@ -17,6 +17,9 @@ public:
     explicit TimeZonePrototype(GlobalObject&);
     virtual void initialize(GlobalObject&) override;
     virtual ~TimeZonePrototype() override = default;
+
+private:
+    JS_DECLARE_NATIVE_FUNCTION(to_string);
 };
 
 }

+ 18 - 0
Userland/Libraries/LibJS/Tests/builtins/Temporal/TimeZone/TimeZone.prototype.toString.js

@@ -0,0 +1,18 @@
+describe("correct behavior", () => {
+    test("length is 0", () => {
+        expect(Temporal.TimeZone.prototype.toString).toHaveLength(0);
+    });
+
+    test("basic functionality", () => {
+        const timeZone = new Temporal.TimeZone("UTC");
+        expect(timeZone.toString()).toBe("UTC");
+    });
+});
+
+test("errors", () => {
+    test("this value must be a Temporal.TimeZone object", () => {
+        expect(() => {
+            Temporal.TimeZone.prototype.toString.call("foo");
+        }).toThrowWithMessage(TypeError, "Not a Temporal.TimeZone");
+    });
+});