Sfoglia il codice sorgente

LibJS: Implement Temporal.Duration.prototype.nanoseconds

Linus Groh 4 anni fa
parent
commit
be5254dcac

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

@@ -244,6 +244,7 @@ namespace JS {
     P(months)                                \
     P(multiline)                             \
     P(name)                                  \
+    P(nanoseconds)                           \
     P(next)                                  \
     P(now)                                   \
     P(of)                                    \

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

@@ -34,6 +34,7 @@ void DurationPrototype::initialize(GlobalObject& global_object)
     define_native_accessor(vm.names.seconds, seconds_getter, {}, Attribute::Configurable);
     define_native_accessor(vm.names.milliseconds, milliseconds_getter, {}, Attribute::Configurable);
     define_native_accessor(vm.names.microseconds, microseconds_getter, {}, Attribute::Configurable);
+    define_native_accessor(vm.names.nanoseconds, nanoseconds_getter, {}, Attribute::Configurable);
 }
 
 static Duration* typed_this(GlobalObject& global_object)
@@ -166,4 +167,17 @@ JS_DEFINE_NATIVE_FUNCTION(DurationPrototype::microseconds_getter)
     return Value(duration->microseconds());
 }
 
+// 7.3.12 get Temporal.Duration.prototype.nanoseconds, https://tc39.es/proposal-temporal/#sec-get-temporal.duration.prototype.nanoseconds
+JS_DEFINE_NATIVE_FUNCTION(DurationPrototype::nanoseconds_getter)
+{
+    // 1. Let duration be the this value.
+    // 2. Perform ? RequireInternalSlot(duration, [[InitializedTemporalDuration]]).
+    auto* duration = typed_this(global_object);
+    if (vm.exception())
+        return {};
+
+    // 3. Return duration.[[Nanoseconds]].
+    return Value(duration->nanoseconds());
+}
+
 }

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

@@ -28,6 +28,7 @@ private:
     JS_DECLARE_NATIVE_FUNCTION(seconds_getter);
     JS_DECLARE_NATIVE_FUNCTION(milliseconds_getter);
     JS_DECLARE_NATIVE_FUNCTION(microseconds_getter);
+    JS_DECLARE_NATIVE_FUNCTION(nanoseconds_getter);
 };
 
 }

+ 14 - 0
Userland/Libraries/LibJS/Tests/builtins/Temporal/Duration/Duration.prototype.nanoseconds.js

@@ -0,0 +1,14 @@
+describe("correct behavior", () => {
+    test("basic functionality", () => {
+        const duration = new Temporal.Duration(0, 0, 0, 0, 0, 0, 0, 0, 0, 123);
+        expect(duration.nanoseconds).toBe(123);
+    });
+});
+
+test("errors", () => {
+    test("this value must be a Temporal.Duration object", () => {
+        expect(() => {
+            Reflect.get(Temporal.Duration.prototype, "nanoseconds", "foo");
+        }).toThrowWithMessage(TypeError, "Not a Temporal.Duration");
+    });
+});