LibJS: Implement Temporal.ZonedDateTime.prototype.toJSON

This commit is contained in:
Luke Wilde 2021-11-10 00:16:06 +00:00 committed by Linus Groh
parent 6856b6168a
commit 5594a492f0
Notes: sideshowbarker 2024-07-18 01:21:08 +09:00
3 changed files with 33 additions and 0 deletions

View file

@ -72,6 +72,7 @@ void ZonedDateTimePrototype::initialize(GlobalObject& global_object)
define_native_function(vm.names.equals, equals, 1, attr);
define_native_function(vm.names.toString, to_string, 0, attr);
define_native_function(vm.names.toLocaleString, to_locale_string, 0, attr);
define_native_function(vm.names.toJSON, to_json, 0, attr);
define_native_function(vm.names.valueOf, value_of, 0, attr);
define_native_function(vm.names.startOfDay, start_of_day, 0, attr);
define_native_function(vm.names.toInstant, to_instant, 0, attr);
@ -875,6 +876,17 @@ JS_DEFINE_NATIVE_FUNCTION(ZonedDateTimePrototype::to_locale_string)
return js_string(vm, TRY(temporal_zoned_date_time_to_string(global_object, *zoned_date_time, "auto"sv, "auto"sv, "auto"sv, "auto"sv)));
}
// 6.3.43 Temporal.ZonedDateTime.prototype.toJSON ( ), https://tc39.es/proposal-temporal/#sec-temporal.zoneddatetime.prototype.tojson
JS_DEFINE_NATIVE_FUNCTION(ZonedDateTimePrototype::to_json)
{
// 1. Let zonedDateTime be the this value.
// 2. Perform ? RequireInternalSlot(zonedDateTime, [[InitializedTemporalZonedDateTime]]).
auto* zoned_date_time = TRY(typed_this_object(global_object));
// 3. Return ? TemporalZonedDateTimeToString(zonedDateTime, "auto", "auto", "auto", "auto").
return js_string(vm, TRY(temporal_zoned_date_time_to_string(global_object, *zoned_date_time, "auto"sv, "auto"sv, "auto"sv, "auto"sv)));
}
// 6.3.44 Temporal.ZonedDateTime.prototype.valueOf ( ), https://tc39.es/proposal-temporal/#sec-temporal.zoneddatetime.prototype.valueof
JS_DEFINE_NATIVE_FUNCTION(ZonedDateTimePrototype::value_of)
{

View file

@ -56,6 +56,7 @@ private:
JS_DECLARE_NATIVE_FUNCTION(equals);
JS_DECLARE_NATIVE_FUNCTION(to_string);
JS_DECLARE_NATIVE_FUNCTION(to_locale_string);
JS_DECLARE_NATIVE_FUNCTION(to_json);
JS_DECLARE_NATIVE_FUNCTION(value_of);
JS_DECLARE_NATIVE_FUNCTION(start_of_day);
JS_DECLARE_NATIVE_FUNCTION(to_instant);

View file

@ -0,0 +1,20 @@
describe("correct behavior", () => {
test("length is 0", () => {
expect(Temporal.ZonedDateTime.prototype.toJSON).toHaveLength(0);
});
test("basic functionality", () => {
const plainDateTime = new Temporal.PlainDateTime(2021, 11, 3, 1, 33, 5, 100, 200, 300);
const timeZone = new Temporal.TimeZone("UTC");
const zonedDateTime = plainDateTime.toZonedDateTime(timeZone);
expect(zonedDateTime.toJSON()).toBe("2021-11-03T01:33:05.1002003+00:00[UTC]");
});
});
describe("errors", () => {
test("this value must be a Temporal.ZonedDateTime object", () => {
expect(() => {
Temporal.ZonedDateTime.prototype.toJSON.call("foo");
}).toThrowWithMessage(TypeError, "Not an object of type Temporal.ZonedDateTime");
});
});