NumberFormatFunction.cpp 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /*
  2. * Copyright (c) 2021-2023, Tim Flynn <trflynn89@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibJS/Runtime/GlobalObject.h>
  7. #include <LibJS/Runtime/Intl/NumberFormat.h>
  8. #include <LibJS/Runtime/Intl/NumberFormatFunction.h>
  9. namespace JS::Intl {
  10. // 15.5.2 Number Format Functions, https://tc39.es/ecma402/#sec-number-format-functions
  11. NonnullGCPtr<NumberFormatFunction> NumberFormatFunction::create(Realm& realm, NumberFormat& number_format)
  12. {
  13. return realm.heap().allocate<NumberFormatFunction>(realm, number_format, realm.intrinsics().function_prototype());
  14. }
  15. NumberFormatFunction::NumberFormatFunction(NumberFormat& number_format, Object& prototype)
  16. : NativeFunction(prototype)
  17. , m_number_format(number_format)
  18. {
  19. }
  20. void NumberFormatFunction::initialize(Realm& realm)
  21. {
  22. auto& vm = this->vm();
  23. Base::initialize(realm);
  24. define_direct_property(vm.names.length, Value(1), Attribute::Configurable);
  25. define_direct_property(vm.names.name, PrimitiveString::create(vm, String {}), Attribute::Configurable);
  26. }
  27. ThrowCompletionOr<Value> NumberFormatFunction::call()
  28. {
  29. auto& vm = this->vm();
  30. // 1. Let nf be F.[[NumberFormat]].
  31. // 2. Assert: Type(nf) is Object and nf has an [[InitializedNumberFormat]] internal slot.
  32. // 3. If value is not provided, let value be undefined.
  33. auto value = vm.argument(0);
  34. // 4. Let x be ? ToIntlMathematicalValue(value).
  35. auto mathematical_value = TRY(to_intl_mathematical_value(vm, value));
  36. // 5. Return ? FormatNumeric(nf, x).
  37. auto formatted = format_numeric(vm, m_number_format, move(mathematical_value));
  38. return PrimitiveString::create(vm, move(formatted));
  39. }
  40. void NumberFormatFunction::visit_edges(Cell::Visitor& visitor)
  41. {
  42. Base::visit_edges(visitor);
  43. visitor.visit(m_number_format);
  44. }
  45. }