NumberFormatFunction.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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. // 1.1.4 Number Format Functions, https://tc39.es/proposal-intl-numberformat-v3/out/numberformat/proposed.html#sec-number-format-functions
  12. NumberFormatFunction* NumberFormatFunction::create(Realm& realm, NumberFormat& number_format)
  13. {
  14. return realm.heap().allocate<NumberFormatFunction>(realm.global_object(), number_format, *realm.global_object().function_prototype());
  15. }
  16. NumberFormatFunction::NumberFormatFunction(NumberFormat& number_format, Object& prototype)
  17. : NativeFunction(prototype)
  18. , m_number_format(number_format)
  19. {
  20. }
  21. void NumberFormatFunction::initialize(Realm& realm)
  22. {
  23. auto& vm = this->vm();
  24. Base::initialize(realm);
  25. define_direct_property(vm.names.length, Value(1), Attribute::Configurable);
  26. define_direct_property(vm.names.name, js_string(vm, String::empty()), Attribute::Configurable);
  27. }
  28. ThrowCompletionOr<Value> NumberFormatFunction::call()
  29. {
  30. auto& global_object = this->global_object();
  31. auto& vm = global_object.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(global_object, value));
  38. // 5. Return ? FormatNumeric(nf, x).
  39. // Note: Our implementation of FormatNumeric does not throw.
  40. auto formatted = format_numeric(global_object, m_number_format, move(mathematical_value));
  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. }