DateTimeFormatFunction.cpp 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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());
  17. }
  18. DateTimeFormatFunction::DateTimeFormatFunction(DateTimeFormat& date_time_format, Object& prototype)
  19. : NativeFunction(prototype)
  20. , m_date_time_format(date_time_format)
  21. {
  22. }
  23. void DateTimeFormatFunction::initialize(Realm& realm)
  24. {
  25. auto& vm = this->vm();
  26. Base::initialize(realm);
  27. define_direct_property(vm.names.length, Value(1), Attribute::Configurable);
  28. define_direct_property(vm.names.name, PrimitiveString::create(vm, DeprecatedString::empty()), Attribute::Configurable);
  29. }
  30. ThrowCompletionOr<Value> DateTimeFormatFunction::call()
  31. {
  32. auto& vm = this->vm();
  33. auto& realm = *vm.current_realm();
  34. auto date = vm.argument(0);
  35. // 1. Let dtf be F.[[DateTimeFormat]].
  36. // 2. Assert: Type(dtf) is Object and dtf has an [[InitializedDateTimeFormat]] internal slot.
  37. double date_value;
  38. // 3. If date is not provided or is undefined, then
  39. if (date.is_undefined()) {
  40. // a. Let x be ! Call(%Date.now%, undefined).
  41. date_value = MUST(JS::call(vm, realm.intrinsics().date_constructor_now_function(), js_undefined())).as_double();
  42. }
  43. // 4. Else,
  44. else {
  45. // a. Let x be ? ToNumber(date).
  46. date_value = TRY(date.to_number(vm)).as_double();
  47. }
  48. // 5. Return ? FormatDateTime(dtf, x).
  49. auto formatted = TRY(format_date_time(vm, m_date_time_format, date_value));
  50. return PrimitiveString::create(vm, move(formatted));
  51. }
  52. void DateTimeFormatFunction::visit_edges(Cell::Visitor& visitor)
  53. {
  54. Base::visit_edges(visitor);
  55. visitor.visit(&m_date_time_format);
  56. }
  57. }