DateTimeFormatFunction.cpp 2.3 KB

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