LibJS: Implement Temporal.PlainYearMonth.prototype.toJSON()

This commit is contained in:
Linus Groh 2021-08-19 00:49:12 +01:00
parent 70fb7bf57e
commit c1c8d7861c
Notes: sideshowbarker 2024-07-18 05:27:16 +09:00
3 changed files with 42 additions and 0 deletions

View file

@ -40,6 +40,7 @@ void PlainYearMonthPrototype::initialize(GlobalObject& global_object)
u8 attr = Attribute::Writable | Attribute::Configurable;
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.getISOFields, get_iso_fields, 0, attr);
}
@ -227,6 +228,23 @@ JS_DEFINE_NATIVE_FUNCTION(PlainYearMonthPrototype::to_locale_string)
return js_string(vm, *string);
}
// 9.3.19 Temporal.PlainYearMonth.prototype.toJSON ( ), https://tc39.es/proposal-temporal/#sec-temporal.plainyearmonth.prototype.tojson
JS_DEFINE_NATIVE_FUNCTION(PlainYearMonthPrototype::to_json)
{
// 1. Let yearMonth be the this value.
// 2. Perform ? RequireInternalSlot(yearMonth, [[InitializedTemporalYearMonth]]).
auto* year_month = typed_this(global_object);
if (vm.exception())
return {};
// 3. Return ? TemporalYearMonthToString(yearMonth, "auto").
auto string = temporal_year_month_to_string(global_object, *year_month, "auto"sv);
if (vm.exception())
return {};
return js_string(vm, *string);
}
// 9.3.20 Temporal.PlainYearMonth.prototype.valueOf ( ), https://tc39.es/proposal-temporal/#sec-temporal.plainyearmonth.prototype.valueof
JS_DEFINE_NATIVE_FUNCTION(PlainYearMonthPrototype::value_of)
{

View file

@ -29,6 +29,7 @@ private:
JS_DECLARE_NATIVE_FUNCTION(in_leap_year_getter);
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(get_iso_fields);
};

View file

@ -0,0 +1,23 @@
describe("correct behavior", () => {
test("length is 0", () => {
expect(Temporal.PlainYearMonth.prototype.toJSON).toHaveLength(0);
});
test("basic functionality", () => {
let plainYearMonth;
plainYearMonth = new Temporal.PlainYearMonth(2021, 7);
expect(plainYearMonth.toJSON()).toBe("2021-07");
plainYearMonth = new Temporal.PlainYearMonth(2021, 7, { toString: () => "foo" }, 6);
expect(plainYearMonth.toJSON()).toBe("2021-07-06[u-ca=foo]");
});
});
describe("errors", () => {
test("this value must be a Temporal.PlainYearMonth object", () => {
expect(() => {
Temporal.PlainYearMonth.prototype.toJSON.call("foo");
}).toThrowWithMessage(TypeError, "Not a Temporal.PlainYearMonth");
});
});