DateTimeFormatFunction.cpp 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*
  2. * Copyright (c) 2021-2022, Tim Flynn <trflynn89@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibJS/Runtime/AbstractOperations.h>
  7. #include <LibJS/Runtime/Date.h>
  8. #include <LibJS/Runtime/DateConstructor.h>
  9. #include <LibJS/Runtime/GlobalObject.h>
  10. #include <LibJS/Runtime/Intl/DateTimeFormat.h>
  11. #include <LibJS/Runtime/Intl/DateTimeFormatFunction.h>
  12. namespace JS::Intl {
  13. // 11.5.5 DateTime Format Functions, https://tc39.es/ecma402/#sec-datetime-format-functions
  14. NonnullGCPtr<DateTimeFormatFunction> DateTimeFormatFunction::create(Realm& realm, DateTimeFormat& date_time_format)
  15. {
  16. return realm.heap().allocate<DateTimeFormatFunction>(realm, date_time_format, realm.intrinsics().function_prototype()).release_allocated_value_but_fixme_should_propagate_errors();
  17. }
  18. DateTimeFormatFunction::DateTimeFormatFunction(DateTimeFormat& date_time_format, Object& prototype)
  19. : NativeFunction(prototype)
  20. , m_date_time_format(date_time_format)
  21. {
  22. }
  23. ThrowCompletionOr<void> DateTimeFormatFunction::initialize(Realm& realm)
  24. {
  25. auto& vm = this->vm();
  26. MUST_OR_THROW_OOM(Base::initialize(realm));
  27. define_direct_property(vm.names.length, Value(1), Attribute::Configurable);
  28. define_direct_property(vm.names.name, PrimitiveString::create(vm, String {}), Attribute::Configurable);
  29. return {};
  30. }
  31. ThrowCompletionOr<Value> DateTimeFormatFunction::call()
  32. {
  33. auto& vm = this->vm();
  34. auto& realm = *vm.current_realm();
  35. auto date = vm.argument(0);
  36. // 1. Let dtf be F.[[DateTimeFormat]].
  37. // 2. Assert: Type(dtf) is Object and dtf has an [[InitializedDateTimeFormat]] internal slot.
  38. double date_value;
  39. // 3. If date is not provided or is undefined, then
  40. if (date.is_undefined()) {
  41. // a. Let x be ! Call(%Date.now%, undefined).
  42. date_value = MUST(JS::call(vm, *realm.intrinsics().date_constructor_now_function(), js_undefined())).as_double();
  43. }
  44. // 4. Else,
  45. else {
  46. // a. Let x be ? ToNumber(date).
  47. date_value = TRY(date.to_number(vm)).as_double();
  48. }
  49. // 5. Return ? FormatDateTime(dtf, x).
  50. auto formatted = TRY(format_date_time(vm, m_date_time_format, date_value));
  51. return PrimitiveString::create(vm, move(formatted));
  52. }
  53. void DateTimeFormatFunction::visit_edges(Cell::Visitor& visitor)
  54. {
  55. Base::visit_edges(visitor);
  56. visitor.visit(m_date_time_format);
  57. }
  58. }