NumberFormatFunction.cpp 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /*
  2. * Copyright (c) 2021, Tim Flynn <trflynn89@pm.me>
  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.1.4 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. Base::initialize(global_object);
  23. define_direct_property(vm().names.length, Value(1), Attribute::Configurable);
  24. }
  25. ThrowCompletionOr<Value> NumberFormatFunction::call()
  26. {
  27. auto& global_object = this->global_object();
  28. auto& vm = global_object.vm();
  29. // 1. Let nf be F.[[NumberFormat]].
  30. // 2. Assert: Type(nf) is Object and nf has an [[InitializedNumberFormat]] internal slot.
  31. // 3. If value is not provided, let value be undefined.
  32. auto value = vm.argument(0);
  33. // 4. Let x be ? ToNumeric(value).
  34. value = TRY(value.to_numeric(global_object));
  35. // FIXME: Support BigInt number formatting.
  36. if (value.is_bigint())
  37. return vm.throw_completion<InternalError>(global_object, ErrorType::NotImplemented, "BigInt number formatting");
  38. // 5. Return ? FormatNumeric(nf, x).
  39. // Note: Our implementation of FormatNumeric does not throw.
  40. auto formatted = format_numeric(m_number_format, value.as_double());
  41. return js_string(vm, move(formatted));
  42. }
  43. void NumberFormatFunction::visit_edges(Cell::Visitor& visitor)
  44. {
  45. Base::visit_edges(visitor);
  46. visitor.visit(&m_number_format);
  47. }
  48. }