DateTimeFormatFunction.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. #include <LibJS/Runtime/ValueInlines.h>
  13. namespace JS::Intl {
  14. // 11.5.4 DateTime Format Functions, https://tc39.es/ecma402/#sec-datetime-format-functions
  15. NonnullGCPtr<DateTimeFormatFunction> DateTimeFormatFunction::create(Realm& realm, DateTimeFormat& date_time_format)
  16. {
  17. return realm.heap().allocate<DateTimeFormatFunction>(realm, date_time_format, realm.intrinsics().function_prototype());
  18. }
  19. DateTimeFormatFunction::DateTimeFormatFunction(DateTimeFormat& date_time_format, Object& prototype)
  20. : NativeFunction(prototype)
  21. , m_date_time_format(date_time_format)
  22. {
  23. }
  24. void DateTimeFormatFunction::initialize(Realm& realm)
  25. {
  26. auto& vm = this->vm();
  27. Base::initialize(realm);
  28. define_direct_property(vm.names.length, Value(1), Attribute::Configurable);
  29. define_direct_property(vm.names.name, PrimitiveString::create(vm, String {}), Attribute::Configurable);
  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. }