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

This commit is contained in:
Linus Groh 2021-07-14 21:12:37 +01:00
parent e01c6adab4
commit 83bbbbe567
Notes: sideshowbarker 2024-07-18 09:00:27 +09:00
3 changed files with 51 additions and 0 deletions

View file

@ -5,6 +5,7 @@
*/
#include <LibJS/Runtime/GlobalObject.h>
#include <LibJS/Runtime/Temporal/Calendar.h>
#include <LibJS/Runtime/Temporal/CalendarPrototype.h>
namespace JS::Temporal {
@ -23,6 +24,35 @@ void CalendarPrototype::initialize(GlobalObject& global_object)
// 12.4.2 Temporal.Calendar.prototype[ @@toStringTag ], https://tc39.es/proposal-temporal/#sec-temporal.calendar.prototype-@@tostringtag
define_direct_property(*vm.well_known_symbol_to_string_tag(), js_string(vm.heap(), "Temporal.Calendar"), Attribute::Configurable);
u8 attr = Attribute::Writable | Attribute::Configurable;
define_native_function(vm.names.toString, to_string, 0, attr);
}
static Calendar* 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<Calendar>(this_object)) {
vm.throw_exception<TypeError>(global_object, ErrorType::NotA, "Temporal.Calendar");
return {};
}
return static_cast<Calendar*>(this_object);
}
// 12.4.23 Temporal.Calendar.prototype.toString ( ), https://tc39.es/proposal-temporal/#sec-temporal.calendar.prototype.tostring
JS_DEFINE_NATIVE_FUNCTION(CalendarPrototype::to_string)
{
// 1. Let calendar be the this value.
// 2. Perform ? RequireInternalSlot(calendar, [[InitializedTemporalCalendar]]).
auto* calendar = typed_this(global_object);
if (vm.exception())
return {};
// 3. Return calendar.[[Identifier]].
return js_string(vm, calendar->identifier());
}
}

View file

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

View file

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