NumberFormatFunction.cpp 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /*
  2. * Copyright (c) 2021-2022, 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. NumberFormatFunction* NumberFormatFunction::create(GlobalObject& global_object, NumberFormat& number_format)
  12. {
  13. return global_object.heap().allocate<NumberFormatFunction>(global_object, number_format, *global_object.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(GlobalObject& global_object)
  21. {
  22. auto& vm = this->vm();
  23. Base::initialize(global_object);
  24. define_direct_property(vm.names.length, Value(1), Attribute::Configurable);
  25. define_direct_property(vm.names.name, js_string(vm, String::empty()), Attribute::Configurable);
  26. }
  27. ThrowCompletionOr<Value> NumberFormatFunction::call()
  28. {
  29. auto& global_object = this->global_object();
  30. auto& vm = global_object.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 ? ToNumeric(value).
  36. value = TRY(value.to_numeric(global_object));
  37. // 5. Return ? FormatNumeric(nf, x).
  38. // Note: Our implementation of FormatNumeric does not throw.
  39. auto formatted = format_numeric(global_object, m_number_format, value);
  40. return js_string(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. }