NumberFormatFunction.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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. // 1.5.2 Number Format Functions, https://tc39.es/proposal-intl-numberformat-v3/out/numberformat/proposed.html#sec-number-format-functions
  12. NonnullGCPtr<NumberFormatFunction> NumberFormatFunction::create(Realm& realm, NumberFormat& number_format)
  13. {
  14. return realm.heap().allocate<NumberFormatFunction>(realm, number_format, *realm.intrinsics().function_prototype()).release_allocated_value_but_fixme_should_propagate_errors();
  15. }
  16. NumberFormatFunction::NumberFormatFunction(NumberFormat& number_format, Object& prototype)
  17. : NativeFunction(prototype)
  18. , m_number_format(number_format)
  19. {
  20. }
  21. ThrowCompletionOr<void> NumberFormatFunction::initialize(Realm& realm)
  22. {
  23. auto& vm = this->vm();
  24. MUST_OR_THROW_OOM(Base::initialize(realm));
  25. define_direct_property(vm.names.length, Value(1), Attribute::Configurable);
  26. define_direct_property(vm.names.name, PrimitiveString::create(vm, String {}), Attribute::Configurable);
  27. return {};
  28. }
  29. ThrowCompletionOr<Value> NumberFormatFunction::call()
  30. {
  31. auto& vm = this->vm();
  32. // 1. Let nf be F.[[NumberFormat]].
  33. // 2. Assert: Type(nf) is Object and nf has an [[InitializedNumberFormat]] internal slot.
  34. // 3. If value is not provided, let value be undefined.
  35. auto value = vm.argument(0);
  36. // 4. Let x be ? ToIntlMathematicalValue(value).
  37. auto mathematical_value = TRY(to_intl_mathematical_value(vm, value));
  38. // 5. Return ? FormatNumeric(nf, x).
  39. auto formatted = TRY(format_numeric(vm, m_number_format, move(mathematical_value)));
  40. return PrimitiveString::create(vm, move(formatted));
  41. }
  42. void NumberFormatFunction::visit_edges(Cell::Visitor& visitor)
  43. {
  44. Base::visit_edges(visitor);
  45. visitor.visit(&m_number_format);
  46. }
  47. }