NumberFormatFunction.cpp 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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, 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. // FIXME: Support BigInt number formatting.
  38. if (value.is_bigint())
  39. return vm.throw_completion<InternalError>(global_object, ErrorType::NotImplemented, "BigInt number formatting");
  40. // 5. Return ? FormatNumeric(nf, x).
  41. // Note: Our implementation of FormatNumeric does not throw.
  42. auto formatted = format_numeric(m_number_format, value.as_double());
  43. return js_string(vm, move(formatted));
  44. }
  45. void NumberFormatFunction::visit_edges(Cell::Visitor& visitor)
  46. {
  47. Base::visit_edges(visitor);
  48. visitor.visit(&m_number_format);
  49. }
  50. }