Jelajahi Sumber

LibJS: Implement Temporal.ZonedDateTime.prototype.toInstant()

Linus Groh 4 tahun lalu
induk
melakukan
96a0c201d5

+ 1 - 0
Userland/Libraries/LibJS/Runtime/CommonPropertyNames.h

@@ -376,6 +376,7 @@ namespace JS {
     P(toDateString)                          \
     P(toFixed)                               \
     P(toGMTString)                           \
+    P(toInstant)                             \
     P(toISOString)                           \
     P(toJSON)                                \
     P(toLocaleDateString)                    \

+ 14 - 0
Userland/Libraries/LibJS/Runtime/Temporal/ZonedDateTimePrototype.cpp

@@ -59,6 +59,7 @@ void ZonedDateTimePrototype::initialize(GlobalObject& global_object)
 
     u8 attr = Attribute::Writable | Attribute::Configurable;
     define_native_function(vm.names.valueOf, value_of, 0, attr);
+    define_native_function(vm.names.toInstant, to_instant, 0, attr);
 }
 
 static ZonedDateTime* typed_this(GlobalObject& global_object)
@@ -702,4 +703,17 @@ JS_DEFINE_NATIVE_FUNCTION(ZonedDateTimePrototype::value_of)
     return {};
 }
 
+// 6.3.46 Temporal.ZonedDateTime.prototype.toInstant ( ), https://tc39.es/proposal-temporal/#sec-temporal.zoneddatetime.prototype.toinstant
+JS_DEFINE_NATIVE_FUNCTION(ZonedDateTimePrototype::to_instant)
+{
+    // 1. Let zonedDateTime be the this value.
+    // 2. Perform ? RequireInternalSlot(zonedDateTime, [[InitializedTemporalZonedDateTime]]).
+    auto* zoned_date_time = typed_this(global_object);
+    if (vm.exception())
+        return {};
+
+    // 3. Return ! CreateTemporalInstant(zonedDateTime.[[Nanoseconds]]).
+    return create_temporal_instant(global_object, zoned_date_time->nanoseconds());
+}
+
 }

+ 1 - 0
Userland/Libraries/LibJS/Runtime/Temporal/ZonedDateTimePrototype.h

@@ -46,6 +46,7 @@ private:
     JS_DECLARE_NATIVE_FUNCTION(offset_nanoseconds_getter);
     JS_DECLARE_NATIVE_FUNCTION(offset_getter);
     JS_DECLARE_NATIVE_FUNCTION(value_of);
+    JS_DECLARE_NATIVE_FUNCTION(to_instant);
 };
 
 }

+ 21 - 0
Userland/Libraries/LibJS/Tests/builtins/Temporal/ZonedDateTime/ZonedDateTime.prototype.toInstant.js

@@ -0,0 +1,21 @@
+describe("correct behavior", () => {
+    test("length is 0", () => {
+        expect(Temporal.ZonedDateTime.prototype.toInstant).toHaveLength(0);
+    });
+
+    test("basic functionality", () => {
+        const timeZone = new Temporal.TimeZone("UTC");
+        const zonedDateTime = new Temporal.ZonedDateTime(1625614921000000000n, timeZone);
+        const instant = zonedDateTime.toInstant();
+        expect(instant).toBeInstanceOf(Temporal.Instant);
+        expect(instant.epochNanoseconds).toBe(1625614921000000000n);
+    });
+});
+
+test("errors", () => {
+    test("this value must be a Temporal.ZonedDateTime object", () => {
+        expect(() => {
+            Temporal.ZonedDateTime.prototype.toInstant.call("foo");
+        }).toThrowWithMessage(TypeError, "Not a Temporal.ZonedDateTime");
+    });
+});