NumberFormatFunction.cpp 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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()).release_allocated_value_but_fixme_should_propagate_errors();
  14. }
  15. NumberFormatFunction::NumberFormatFunction(NumberFormat& number_format, Object& prototype)
  16. : NativeFunction(prototype)
  17. , m_number_format(number_format)
  18. {
  19. }
  20. ThrowCompletionOr<void> NumberFormatFunction::initialize(Realm& realm)
  21. {
  22. auto& vm = this->vm();
  23. MUST_OR_THROW_OOM(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. return {};
  27. }
  28. ThrowCompletionOr<Value> NumberFormatFunction::call()
  29. {
  30. auto& vm = this->vm();
  31. // 1. Let nf be F.[[NumberFormat]].
  32. // 2. Assert: Type(nf) is Object and nf has an [[InitializedNumberFormat]] internal slot.
  33. // 3. If value is not provided, let value be undefined.
  34. auto value = vm.argument(0);
  35. // 4. Let x be ? ToIntlMathematicalValue(value).
  36. auto mathematical_value = TRY(to_intl_mathematical_value(vm, value));
  37. // 5. Return ? FormatNumeric(nf, x).
  38. auto formatted = TRY(format_numeric(vm, m_number_format, move(mathematical_value)));
  39. return PrimitiveString::create(vm, move(formatted));
  40. }
  41. void NumberFormatFunction::visit_edges(Cell::Visitor& visitor)
  42. {
  43. Base::visit_edges(visitor);
  44. visitor.visit(m_number_format);
  45. }
  46. }