DateTimeFormatFunction.cpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /*
  2. * Copyright (c) 2021, Tim Flynn <trflynn89@pm.me>
  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.1.6 DateTime Format Functions, https://tc39.es/ecma402/#sec-datetime-format-functions
  14. DateTimeFormatFunction* DateTimeFormatFunction::create(GlobalObject& global_object, DateTimeFormat& date_time_format)
  15. {
  16. return global_object.heap().allocate<DateTimeFormatFunction>(global_object, date_time_format, *global_object.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(GlobalObject& global_object)
  24. {
  25. auto& vm = this->vm();
  26. Base::initialize(global_object);
  27. define_direct_property(vm.names.length, Value(1), Attribute::Configurable);
  28. define_direct_property(vm.names.name, js_string(vm, String::empty()), Attribute::Configurable);
  29. }
  30. ThrowCompletionOr<Value> DateTimeFormatFunction::call()
  31. {
  32. auto& global_object = this->global_object();
  33. auto& vm = global_object.vm();
  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. // 3. If date is not provided or is undefined, then
  38. if (date.is_undefined()) {
  39. // a. Let x be Call(%Date.now%, undefined).
  40. date = MUST(JS::call(global_object, global_object.date_constructor_now_function(), js_undefined()));
  41. }
  42. // 4. Else,
  43. else {
  44. // a. Let x be ? ToNumber(date).
  45. date = TRY(date.to_number(global_object));
  46. }
  47. // 5. Return ? FormatDateTime(dtf, x).
  48. auto formatted = TRY(format_date_time(global_object, m_date_time_format, date));
  49. return js_string(vm, move(formatted));
  50. }
  51. void DateTimeFormatFunction::visit_edges(Cell::Visitor& visitor)
  52. {
  53. Base::visit_edges(visitor);
  54. visitor.visit(&m_date_time_format);
  55. }
  56. }