MathematicalValue.cpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. /*
  2. * Copyright (c) 2022-2024, Tim Flynn <trflynn89@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibJS/Runtime/Intl/MathematicalValue.h>
  7. namespace JS::Intl {
  8. bool MathematicalValue::is_number() const
  9. {
  10. return m_value.has<double>();
  11. }
  12. double MathematicalValue::as_number() const
  13. {
  14. VERIFY(is_number());
  15. return m_value.get<double>();
  16. }
  17. bool MathematicalValue::is_string() const
  18. {
  19. return m_value.has<String>();
  20. }
  21. String const& MathematicalValue::as_string() const
  22. {
  23. VERIFY(is_string());
  24. return m_value.get<String>();
  25. }
  26. bool MathematicalValue::is_mathematical_value() const
  27. {
  28. return is_number() || is_string();
  29. }
  30. bool MathematicalValue::is_positive_infinity() const
  31. {
  32. if (is_mathematical_value())
  33. return false;
  34. return m_value.get<Symbol>() == Symbol::PositiveInfinity;
  35. }
  36. bool MathematicalValue::is_negative_infinity() const
  37. {
  38. if (is_mathematical_value())
  39. return false;
  40. return m_value.get<Symbol>() == Symbol::NegativeInfinity;
  41. }
  42. bool MathematicalValue::is_negative_zero() const
  43. {
  44. if (is_mathematical_value())
  45. return false;
  46. return m_value.get<Symbol>() == Symbol::NegativeZero;
  47. }
  48. bool MathematicalValue::is_nan() const
  49. {
  50. if (is_mathematical_value())
  51. return false;
  52. return m_value.get<Symbol>() == Symbol::NotANumber;
  53. }
  54. ::Locale::NumberFormat::Value MathematicalValue::to_value() const
  55. {
  56. return m_value.visit(
  57. [](double value) -> ::Locale::NumberFormat::Value {
  58. return value;
  59. },
  60. [](String const& value) -> ::Locale::NumberFormat::Value {
  61. return value;
  62. },
  63. [](auto symbol) -> ::Locale::NumberFormat::Value {
  64. switch (symbol) {
  65. case Symbol::PositiveInfinity:
  66. return js_infinity().as_double();
  67. case Symbol::NegativeInfinity:
  68. return js_negative_infinity().as_double();
  69. case Symbol::NegativeZero:
  70. return -0.0;
  71. case Symbol::NotANumber:
  72. return js_nan().as_double();
  73. }
  74. VERIFY_NOT_REACHED();
  75. });
  76. }
  77. MathematicalValue::ValueType MathematicalValue::value_from_number(double number)
  78. {
  79. Value value(number);
  80. if (value.is_positive_infinity())
  81. return Symbol::PositiveInfinity;
  82. if (value.is_negative_infinity())
  83. return Symbol::NegativeInfinity;
  84. if (value.is_negative_zero())
  85. return Symbol::NegativeZero;
  86. if (value.is_nan())
  87. return Symbol::NotANumber;
  88. return number;
  89. }
  90. }