NumberFormat.cpp 75 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674
  1. /*
  2. * Copyright (c) 2021, Tim Flynn <trflynn89@pm.me>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Array.h>
  7. #include <AK/Utf8View.h>
  8. #include <LibJS/Runtime/Array.h>
  9. #include <LibJS/Runtime/GlobalObject.h>
  10. #include <LibJS/Runtime/Intl/NumberFormat.h>
  11. #include <LibJS/Runtime/Intl/NumberFormatFunction.h>
  12. #include <LibUnicode/CurrencyCode.h>
  13. #include <math.h>
  14. #include <stdlib.h>
  15. namespace JS::Intl {
  16. Vector<StringView> const& NumberFormat::relevant_extension_keys()
  17. {
  18. // 15.3.3 Internal slots, https://tc39.es/ecma402/#sec-intl.numberformat-internal-slots
  19. // The value of the [[RelevantExtensionKeys]] internal slot is « "nu" ».
  20. static Vector<StringView> relevant_extension_keys { "nu"sv };
  21. return relevant_extension_keys;
  22. }
  23. // 15 NumberFormat Objects, https://tc39.es/ecma402/#numberformat-objects
  24. NumberFormat::NumberFormat(Object& prototype)
  25. : Object(prototype)
  26. {
  27. }
  28. void NumberFormat::visit_edges(Cell::Visitor& visitor)
  29. {
  30. Base::visit_edges(visitor);
  31. if (m_bound_format)
  32. visitor.visit(m_bound_format);
  33. }
  34. void NumberFormat::set_style(StringView style)
  35. {
  36. if (style == "decimal"sv)
  37. m_style = Style::Decimal;
  38. else if (style == "percent"sv)
  39. m_style = Style::Percent;
  40. else if (style == "currency"sv)
  41. m_style = Style::Currency;
  42. else if (style == "unit"sv)
  43. m_style = Style::Unit;
  44. else
  45. VERIFY_NOT_REACHED();
  46. }
  47. StringView NumberFormat::style_string() const
  48. {
  49. switch (m_style) {
  50. case Style::Decimal:
  51. return "decimal"sv;
  52. case Style::Percent:
  53. return "percent"sv;
  54. case Style::Currency:
  55. return "currency"sv;
  56. case Style::Unit:
  57. return "unit"sv;
  58. default:
  59. VERIFY_NOT_REACHED();
  60. }
  61. }
  62. void NumberFormat::set_currency_display(StringView currency_display)
  63. {
  64. m_resolved_currency_display.clear();
  65. if (currency_display == "code"sv)
  66. m_currency_display = CurrencyDisplay::Code;
  67. else if (currency_display == "symbol"sv)
  68. m_currency_display = CurrencyDisplay::Symbol;
  69. else if (currency_display == "narrowSymbol"sv)
  70. m_currency_display = CurrencyDisplay::NarrowSymbol;
  71. else if (currency_display == "name"sv)
  72. m_currency_display = CurrencyDisplay::Name;
  73. else
  74. VERIFY_NOT_REACHED();
  75. }
  76. StringView NumberFormat::resolve_currency_display()
  77. {
  78. if (m_resolved_currency_display.has_value())
  79. return *m_resolved_currency_display;
  80. switch (currency_display()) {
  81. case NumberFormat::CurrencyDisplay::Code:
  82. m_resolved_currency_display = currency();
  83. break;
  84. case NumberFormat::CurrencyDisplay::Symbol:
  85. m_resolved_currency_display = Unicode::get_locale_currency_mapping(data_locale(), currency(), Unicode::Style::Short);
  86. break;
  87. case NumberFormat::CurrencyDisplay::NarrowSymbol:
  88. m_resolved_currency_display = Unicode::get_locale_currency_mapping(data_locale(), currency(), Unicode::Style::Narrow);
  89. break;
  90. case NumberFormat::CurrencyDisplay::Name:
  91. m_resolved_currency_display = Unicode::get_locale_currency_mapping(data_locale(), currency(), Unicode::Style::Numeric);
  92. break;
  93. default:
  94. VERIFY_NOT_REACHED();
  95. }
  96. if (!m_resolved_currency_display.has_value())
  97. m_resolved_currency_display = currency();
  98. return *m_resolved_currency_display;
  99. }
  100. StringView NumberFormat::currency_display_string() const
  101. {
  102. VERIFY(m_currency_display.has_value());
  103. switch (*m_currency_display) {
  104. case CurrencyDisplay::Code:
  105. return "code"sv;
  106. case CurrencyDisplay::Symbol:
  107. return "symbol"sv;
  108. case CurrencyDisplay::NarrowSymbol:
  109. return "narrowSymbol"sv;
  110. case CurrencyDisplay::Name:
  111. return "name"sv;
  112. default:
  113. VERIFY_NOT_REACHED();
  114. }
  115. }
  116. void NumberFormat::set_currency_sign(StringView currency_sign)
  117. {
  118. if (currency_sign == "standard"sv)
  119. m_currency_sign = CurrencySign::Standard;
  120. else if (currency_sign == "accounting"sv)
  121. m_currency_sign = CurrencySign::Accounting;
  122. else
  123. VERIFY_NOT_REACHED();
  124. }
  125. StringView NumberFormat::currency_sign_string() const
  126. {
  127. VERIFY(m_currency_sign.has_value());
  128. switch (*m_currency_sign) {
  129. case CurrencySign::Standard:
  130. return "standard"sv;
  131. case CurrencySign::Accounting:
  132. return "accounting"sv;
  133. default:
  134. VERIFY_NOT_REACHED();
  135. }
  136. }
  137. void NumberFormat::set_unit_display(StringView unit_display)
  138. {
  139. if (unit_display == "short"sv)
  140. m_unit_display = UnitDisplay::Short;
  141. else if (unit_display == "narrow"sv)
  142. m_unit_display = UnitDisplay::Narrow;
  143. else if (unit_display == "long"sv)
  144. m_unit_display = UnitDisplay::Long;
  145. else
  146. VERIFY_NOT_REACHED();
  147. }
  148. StringView NumberFormat::unit_display_string() const
  149. {
  150. VERIFY(m_unit_display.has_value());
  151. switch (*m_unit_display) {
  152. case UnitDisplay::Short:
  153. return "short"sv;
  154. case UnitDisplay::Narrow:
  155. return "narrow"sv;
  156. case UnitDisplay::Long:
  157. return "long"sv;
  158. default:
  159. VERIFY_NOT_REACHED();
  160. }
  161. }
  162. StringView NumberFormat::rounding_type_string() const
  163. {
  164. switch (m_rounding_type) {
  165. case RoundingType::SignificantDigits:
  166. return "significantDigits"sv;
  167. case RoundingType::FractionDigits:
  168. return "fractionDigits"sv;
  169. case RoundingType::CompactRounding:
  170. return "compactRounding"sv;
  171. default:
  172. VERIFY_NOT_REACHED();
  173. }
  174. }
  175. void NumberFormat::set_notation(StringView notation)
  176. {
  177. if (notation == "standard"sv)
  178. m_notation = Notation::Standard;
  179. else if (notation == "scientific"sv)
  180. m_notation = Notation::Scientific;
  181. else if (notation == "engineering"sv)
  182. m_notation = Notation::Engineering;
  183. else if (notation == "compact"sv)
  184. m_notation = Notation::Compact;
  185. else
  186. VERIFY_NOT_REACHED();
  187. }
  188. StringView NumberFormat::notation_string() const
  189. {
  190. switch (m_notation) {
  191. case Notation::Standard:
  192. return "standard"sv;
  193. case Notation::Scientific:
  194. return "scientific"sv;
  195. case Notation::Engineering:
  196. return "engineering"sv;
  197. case Notation::Compact:
  198. return "compact"sv;
  199. default:
  200. VERIFY_NOT_REACHED();
  201. }
  202. }
  203. void NumberFormat::set_compact_display(StringView compact_display)
  204. {
  205. if (compact_display == "short"sv)
  206. m_compact_display = CompactDisplay::Short;
  207. else if (compact_display == "long"sv)
  208. m_compact_display = CompactDisplay::Long;
  209. else
  210. VERIFY_NOT_REACHED();
  211. }
  212. StringView NumberFormat::compact_display_string() const
  213. {
  214. VERIFY(m_compact_display.has_value());
  215. switch (*m_compact_display) {
  216. case CompactDisplay::Short:
  217. return "short"sv;
  218. case CompactDisplay::Long:
  219. return "long"sv;
  220. default:
  221. VERIFY_NOT_REACHED();
  222. }
  223. }
  224. void NumberFormat::set_sign_display(StringView sign_display)
  225. {
  226. if (sign_display == "auto"sv)
  227. m_sign_display = SignDisplay::Auto;
  228. else if (sign_display == "never"sv)
  229. m_sign_display = SignDisplay::Never;
  230. else if (sign_display == "always"sv)
  231. m_sign_display = SignDisplay::Always;
  232. else if (sign_display == "exceptZero"sv)
  233. m_sign_display = SignDisplay::ExceptZero;
  234. else
  235. VERIFY_NOT_REACHED();
  236. }
  237. StringView NumberFormat::sign_display_string() const
  238. {
  239. switch (m_sign_display) {
  240. case SignDisplay::Auto:
  241. return "auto"sv;
  242. case SignDisplay::Never:
  243. return "never"sv;
  244. case SignDisplay::Always:
  245. return "always"sv;
  246. case SignDisplay::ExceptZero:
  247. return "exceptZero"sv;
  248. default:
  249. VERIFY_NOT_REACHED();
  250. }
  251. }
  252. static ALWAYS_INLINE int log10floor(double value)
  253. {
  254. return static_cast<int>(floor(log10(value)));
  255. }
  256. // 15.1.1 SetNumberFormatDigitOptions ( intlObj, options, mnfdDefault, mxfdDefault, notation ), https://tc39.es/ecma402/#sec-setnfdigitoptions
  257. ThrowCompletionOr<void> set_number_format_digit_options(GlobalObject& global_object, NumberFormat& intl_object, Object const& options, int default_min_fraction_digits, int default_max_fraction_digits, NumberFormat::Notation notation)
  258. {
  259. auto& vm = global_object.vm();
  260. // 1. Let mnid be ? GetNumberOption(options, "minimumIntegerDigits,", 1, 21, 1).
  261. auto min_integer_digits = TRY(get_number_option(global_object, options, vm.names.minimumIntegerDigits, 1, 21, 1));
  262. // 2. Let mnfd be ? Get(options, "minimumFractionDigits").
  263. auto min_fraction_digits = TRY(options.get(vm.names.minimumFractionDigits));
  264. // 3. Let mxfd be ? Get(options, "maximumFractionDigits").
  265. auto max_fraction_digits = TRY(options.get(vm.names.maximumFractionDigits));
  266. // 4. Let mnsd be ? Get(options, "minimumSignificantDigits").
  267. auto min_significant_digits = TRY(options.get(vm.names.minimumSignificantDigits));
  268. // 5. Let mxsd be ? Get(options, "maximumSignificantDigits").
  269. auto max_significant_digits = TRY(options.get(vm.names.maximumSignificantDigits));
  270. // 6. Set intlObj.[[MinimumIntegerDigits]] to mnid.
  271. intl_object.set_min_integer_digits(*min_integer_digits);
  272. // 7. If mnsd is not undefined or mxsd is not undefined, then
  273. // a. Let hasSd be true.
  274. // 8. Else,
  275. // a. Let hasSd be false.
  276. bool has_significant_digits = !min_significant_digits.is_undefined() || !max_significant_digits.is_undefined();
  277. // 9. If mnfd is not undefined or mxfd is not undefined, then
  278. // a. Let hasFd be true.
  279. // 10. Else,
  280. // a. Let hasFd be false.
  281. bool has_fraction_digits = !min_fraction_digits.is_undefined() || !max_fraction_digits.is_undefined();
  282. // 11. Let needSd be hasSd.
  283. bool need_significant_digits = has_significant_digits;
  284. // 12. If hasSd is true, or hasFd is false and notation is "compact", then
  285. // a. Let needFd be false.
  286. // 13. Else,
  287. // a. Let needFd be true.
  288. bool need_fraction_digits = !has_significant_digits && (has_fraction_digits || (notation != NumberFormat::Notation::Compact));
  289. // 14. If needSd is true, then
  290. if (need_significant_digits) {
  291. // a. Assert: hasSd is true.
  292. VERIFY(has_significant_digits);
  293. // b. Set mnsd to ? DefaultNumberOption(mnsd, 1, 21, 1).
  294. auto min_digits = TRY(default_number_option(global_object, min_significant_digits, 1, 21, 1));
  295. // c. Set mxsd to ? DefaultNumberOption(mxsd, mnsd, 21, 21).
  296. auto max_digits = TRY(default_number_option(global_object, max_significant_digits, *min_digits, 21, 21));
  297. // d. Set intlObj.[[MinimumSignificantDigits]] to mnsd.
  298. intl_object.set_min_significant_digits(*min_digits);
  299. // e. Set intlObj.[[MaximumSignificantDigits]] to mxsd.
  300. intl_object.set_max_significant_digits(*max_digits);
  301. }
  302. // 15. If needFd is true, then
  303. if (need_fraction_digits) {
  304. // a. If hasFd is true, then
  305. if (has_fraction_digits) {
  306. // i. Set mnfd to ? DefaultNumberOption(mnfd, 0, 20, undefined).
  307. auto min_digits = TRY(default_number_option(global_object, min_fraction_digits, 0, 20, {}));
  308. // ii. Set mxfd to ? DefaultNumberOption(mxfd, 0, 20, undefined).
  309. auto max_digits = TRY(default_number_option(global_object, max_fraction_digits, 0, 20, {}));
  310. // iii. If mnfd is undefined, set mnfd to min(mnfdDefault, mxfd).
  311. if (!min_digits.has_value())
  312. min_digits = min(default_min_fraction_digits, *max_digits);
  313. // iv. Else if mxfd is undefined, set mxfd to max(mxfdDefault, mnfd).
  314. else if (!max_digits.has_value())
  315. max_digits = max(default_max_fraction_digits, *min_digits);
  316. // v. Else if mnfd is greater than mxfd, throw a RangeError exception.
  317. else if (*min_digits > *max_digits)
  318. return vm.throw_completion<RangeError>(global_object, ErrorType::IntlMinimumExceedsMaximum, *min_digits, *max_digits);
  319. // vi. Set intlObj.[[MinimumFractionDigits]] to mnfd.
  320. intl_object.set_min_fraction_digits(*min_digits);
  321. // vii. Set intlObj.[[MaximumFractionDigits]] to mxfd.
  322. intl_object.set_max_fraction_digits(*max_digits);
  323. }
  324. // b. Else,
  325. else {
  326. // i. Set intlObj.[[MinimumFractionDigits]] to mnfdDefault.
  327. intl_object.set_min_fraction_digits(default_min_fraction_digits);
  328. // ii. Set intlObj.[[MaximumFractionDigits]] to mxfdDefault.
  329. intl_object.set_max_fraction_digits(default_max_fraction_digits);
  330. }
  331. }
  332. // 16. If needSd is false and needFd is false, then
  333. if (!need_significant_digits && !need_fraction_digits) {
  334. // a. Set intlObj.[[RoundingType]] to compactRounding.
  335. intl_object.set_rounding_type(NumberFormat::RoundingType::CompactRounding);
  336. }
  337. // 17. Else if hasSd is true, then
  338. else if (has_significant_digits) {
  339. // a. Set intlObj.[[RoundingType]] to significantDigits.
  340. intl_object.set_rounding_type(NumberFormat::RoundingType::SignificantDigits);
  341. }
  342. // 18. Else,
  343. else {
  344. // a. Set intlObj.[[RoundingType]] to fractionDigits.
  345. intl_object.set_rounding_type(NumberFormat::RoundingType::FractionDigits);
  346. }
  347. return {};
  348. }
  349. // 15.1.2 InitializeNumberFormat ( numberFormat, locales, options ), https://tc39.es/ecma402/#sec-initializenumberformat
  350. ThrowCompletionOr<NumberFormat*> initialize_number_format(GlobalObject& global_object, NumberFormat& number_format, Value locales_value, Value options_value)
  351. {
  352. auto& vm = global_object.vm();
  353. // 1. Let requestedLocales be ? CanonicalizeLocaleList(locales).
  354. auto requested_locales = TRY(canonicalize_locale_list(global_object, locales_value));
  355. // 2. Set options to ? CoerceOptionsToObject(options).
  356. auto* options = TRY(coerce_options_to_object(global_object, options_value));
  357. // 3. Let opt be a new Record.
  358. LocaleOptions opt {};
  359. // 4. Let matcher be ? GetOption(options, "localeMatcher", "string", « "lookup", "best fit" », "best fit").
  360. auto matcher = TRY(get_option(global_object, *options, vm.names.localeMatcher, Value::Type::String, { "lookup"sv, "best fit"sv }, "best fit"sv));
  361. // 5. Set opt.[[localeMatcher]] to matcher.
  362. opt.locale_matcher = matcher;
  363. // 6. Let numberingSystem be ? GetOption(options, "numberingSystem", "string", undefined, undefined).
  364. auto numbering_system = TRY(get_option(global_object, *options, vm.names.numberingSystem, Value::Type::String, {}, Empty {}));
  365. // 7. If numberingSystem is not undefined, then
  366. if (!numbering_system.is_undefined()) {
  367. // a. If numberingSystem does not match the Unicode Locale Identifier type nonterminal, throw a RangeError exception.
  368. if (!Unicode::is_type_identifier(numbering_system.as_string().string()))
  369. return vm.throw_completion<RangeError>(global_object, ErrorType::OptionIsNotValidValue, numbering_system, "numberingSystem"sv);
  370. // 8. Set opt.[[nu]] to numberingSystem.
  371. opt.nu = numbering_system.as_string().string();
  372. }
  373. // 9. Let localeData be %NumberFormat%.[[LocaleData]].
  374. // 10. Let r be ResolveLocale(%NumberFormat%.[[AvailableLocales]], requestedLocales, opt, %NumberFormat%.[[RelevantExtensionKeys]], localeData).
  375. auto result = resolve_locale(requested_locales, opt, NumberFormat::relevant_extension_keys());
  376. // 11. Set numberFormat.[[Locale]] to r.[[locale]].
  377. number_format.set_locale(move(result.locale));
  378. // 12. Set numberFormat.[[DataLocale]] to r.[[dataLocale]].
  379. number_format.set_data_locale(move(result.data_locale));
  380. // 13. Set numberFormat.[[NumberingSystem]] to r.[[nu]].
  381. number_format.set_numbering_system(result.nu.release_value());
  382. // 14. Perform ? SetNumberFormatUnitOptions(numberFormat, options).
  383. TRY(set_number_format_unit_options(global_object, number_format, *options));
  384. // 15. Let style be numberFormat.[[Style]].
  385. auto style = number_format.style();
  386. int default_min_fraction_digits = 0;
  387. int default_max_fraction_digits = 0;
  388. // 16. If style is "currency", then
  389. if (style == NumberFormat::Style::Currency) {
  390. // a. Let currency be numberFormat.[[Currency]].
  391. auto const& currency = number_format.currency();
  392. // b. Let cDigits be CurrencyDigits(currency).
  393. int digits = currency_digits(currency);
  394. // c. Let mnfdDefault be cDigits.
  395. default_min_fraction_digits = digits;
  396. // d. Let mxfdDefault be cDigits.
  397. default_max_fraction_digits = digits;
  398. }
  399. // 17. Else,
  400. else {
  401. // a. Let mnfdDefault be 0.
  402. default_min_fraction_digits = 0;
  403. // b. If style is "percent", then
  404. // i. Let mxfdDefault be 0.
  405. // c. Else,
  406. // i. Let mxfdDefault be 3.
  407. default_max_fraction_digits = style == NumberFormat::Style::Percent ? 0 : 3;
  408. }
  409. // 18. Let notation be ? GetOption(options, "notation", "string", « "standard", "scientific", "engineering", "compact" », "standard").
  410. auto notation = TRY(get_option(global_object, *options, vm.names.notation, Value::Type::String, { "standard"sv, "scientific"sv, "engineering"sv, "compact"sv }, "standard"sv));
  411. // 19. Set numberFormat.[[Notation]] to notation.
  412. number_format.set_notation(notation.as_string().string());
  413. // 20. Perform ? SetNumberFormatDigitOptions(numberFormat, options, mnfdDefault, mxfdDefault, notation).
  414. TRY(set_number_format_digit_options(global_object, number_format, *options, default_min_fraction_digits, default_max_fraction_digits, number_format.notation()));
  415. // 21. Let compactDisplay be ? GetOption(options, "compactDisplay", "string", « "short", "long" », "short").
  416. auto compact_display = TRY(get_option(global_object, *options, vm.names.compactDisplay, Value::Type::String, { "short"sv, "long"sv }, "short"sv));
  417. // 22. If notation is "compact", then
  418. if (number_format.notation() == NumberFormat::Notation::Compact) {
  419. // a. Set numberFormat.[[CompactDisplay]] to compactDisplay.
  420. number_format.set_compact_display(compact_display.as_string().string());
  421. }
  422. // 23. Let useGrouping be ? GetOption(options, "useGrouping", "boolean", undefined, true).
  423. auto use_grouping = TRY(get_option(global_object, *options, vm.names.useGrouping, Value::Type::Boolean, {}, true));
  424. // 24. Set numberFormat.[[UseGrouping]] to useGrouping.
  425. number_format.set_use_grouping(use_grouping.as_bool());
  426. // 25. Let signDisplay be ? GetOption(options, "signDisplay", "string", « "auto", "never", "always", "exceptZero" », "auto").
  427. auto sign_display = TRY(get_option(global_object, *options, vm.names.signDisplay, Value::Type::String, { "auto"sv, "never"sv, "always"sv, "exceptZero"sv }, "auto"sv));
  428. // 26. Set numberFormat.[[SignDisplay]] to signDisplay.
  429. number_format.set_sign_display(sign_display.as_string().string());
  430. // 27. Return numberFormat.
  431. return &number_format;
  432. }
  433. // 15.1.3 CurrencyDigits ( currency ), https://tc39.es/ecma402/#sec-currencydigits
  434. int currency_digits(StringView currency)
  435. {
  436. // 1. If the ISO 4217 currency and funds code list contains currency as an alphabetic code, return the minor
  437. // unit value corresponding to the currency from the list; otherwise, return 2.
  438. if (auto currency_code = Unicode::get_currency_code(currency); currency_code.has_value())
  439. return currency_code->minor_unit.value_or(2);
  440. return 2;
  441. }
  442. // 15.1.5 FormatNumericToString ( intlObject, x ), https://tc39.es/ecma402/#sec-formatnumberstring
  443. FormatResult format_numeric_to_string(NumberFormat& number_format, double number)
  444. {
  445. // 1. If x < 0 or x is -0𝔽, let isNegative be true; else let isNegative be false.
  446. bool is_negative = (number < 0.0) || Value(number).is_negative_zero();
  447. // 2. If isNegative, then
  448. if (is_negative) {
  449. // a. Let x be -x.
  450. number *= -1;
  451. }
  452. RawFormatResult result {};
  453. switch (number_format.rounding_type()) {
  454. // 3. If intlObject.[[RoundingType]] is significantDigits, then
  455. case NumberFormat::RoundingType::SignificantDigits:
  456. // a. Let result be ToRawPrecision(x, intlObject.[[MinimumSignificantDigits]], intlObject.[[MaximumSignificantDigits]]).
  457. result = to_raw_precision(number, number_format.min_significant_digits(), number_format.max_significant_digits());
  458. break;
  459. // 4. Else if intlObject.[[RoundingType]] is fractionDigits, then
  460. case NumberFormat::RoundingType::FractionDigits:
  461. // a. Let result be ToRawFixed(x, intlObject.[[MinimumFractionDigits]], intlObject.[[MaximumFractionDigits]]).
  462. result = to_raw_fixed(number, number_format.min_fraction_digits(), number_format.max_fraction_digits());
  463. break;
  464. // 5. Else,
  465. case NumberFormat::RoundingType::CompactRounding:
  466. // a. Assert: intlObject.[[RoundingType]] is compactRounding.
  467. // b. Let result be ToRawPrecision(x, 1, 2).
  468. result = to_raw_precision(number, 1, 2);
  469. // c. If result.[[IntegerDigitsCount]] > 1, then
  470. if (result.digits > 1) {
  471. // i. Let result be ToRawFixed(x, 0, 0).
  472. result = to_raw_fixed(number, 0, 0);
  473. }
  474. break;
  475. default:
  476. VERIFY_NOT_REACHED();
  477. }
  478. // 6. Let x be result.[[RoundedNumber]].
  479. number = result.rounded_number;
  480. // 7. Let string be result.[[FormattedString]].
  481. auto string = move(result.formatted_string);
  482. // 8. Let int be result.[[IntegerDigitsCount]].
  483. int digits = result.digits;
  484. // 9. Let minInteger be intlObject.[[MinimumIntegerDigits]].
  485. int min_integer = number_format.min_integer_digits();
  486. // 10. If int < minInteger, then
  487. if (digits < min_integer) {
  488. // a. Let forwardZeros be the String consisting of minInteger–int occurrences of the character "0".
  489. auto forward_zeros = String::repeated('0', min_integer - digits);
  490. // b. Set string to the string-concatenation of forwardZeros and string.
  491. string = String::formatted("{}{}", forward_zeros, string);
  492. }
  493. // 11. If isNegative, then
  494. if (is_negative) {
  495. // a. Let x be -x.
  496. number *= -1;
  497. }
  498. // 12. Return the Record { [[RoundedNumber]]: x, [[FormattedString]]: string }.
  499. return { move(string), number };
  500. }
  501. // 15.1.6 PartitionNumberPattern ( numberFormat, x ), https://tc39.es/ecma402/#sec-partitionnumberpattern
  502. Vector<PatternPartition> partition_number_pattern(NumberFormat& number_format, double number)
  503. {
  504. // 1. Let exponent be 0.
  505. int exponent = 0;
  506. String formatted_string;
  507. // 2. If x is NaN, then
  508. if (Value(number).is_nan()) {
  509. // a. Let n be an implementation- and locale-dependent (ILD) String value indicating the NaN value.
  510. formatted_string = Unicode::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), "nan"sv).value_or("NaN"sv);
  511. }
  512. // 3. Else if x is a non-finite Number, then
  513. else if (!Value(number).is_finite_number()) {
  514. // a. Let n be an ILD String value indicating infinity.
  515. formatted_string = Unicode::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), "infinity"sv).value_or("infinity"sv);
  516. }
  517. // 4. Else,
  518. else {
  519. // a. If numberFormat.[[Style]] is "percent", let x be 100 × x.
  520. if (number_format.style() == NumberFormat::Style::Percent)
  521. number = number * 100;
  522. // b. Let exponent be ComputeExponent(numberFormat, x).
  523. exponent = compute_exponent(number_format, number);
  524. // c. Let x be x × 10^(-exponent).
  525. number *= pow(10, -exponent);
  526. // d. Let formatNumberResult be FormatNumericToString(numberFormat, x).
  527. auto format_number_result = format_numeric_to_string(number_format, number);
  528. // e. Let n be formatNumberResult.[[FormattedString]].
  529. formatted_string = move(format_number_result.formatted_string);
  530. // f. Let x be formatNumberResult.[[RoundedNumber]].
  531. number = format_number_result.rounded_number;
  532. }
  533. Unicode::NumberFormat found_pattern {};
  534. // 5. Let pattern be GetNumberFormatPattern(numberFormat, x).
  535. auto pattern = get_number_format_pattern(number_format, number, found_pattern);
  536. if (!pattern.has_value())
  537. return {};
  538. // 6. Let result be a new empty List.
  539. Vector<PatternPartition> result;
  540. // 7. Let patternParts be PartitionPattern(pattern).
  541. auto pattern_parts = pattern->visit([](auto const& p) { return partition_pattern(p); });
  542. // 8. For each Record { [[Type]], [[Value]] } patternPart of patternParts, do
  543. for (auto& pattern_part : pattern_parts) {
  544. // a. Let p be patternPart.[[Type]].
  545. auto part = pattern_part.type;
  546. // b. If p is "literal", then
  547. if (part == "literal"sv) {
  548. // i. Append a new Record { [[Type]]: "literal", [[Value]]: patternPart.[[Value]] } as the last element of result.
  549. result.append({ "literal"sv, move(pattern_part.value) });
  550. }
  551. // c. Else if p is equal to "number", then
  552. else if (part == "number"sv) {
  553. // i. Let notationSubParts be PartitionNotationSubPattern(numberFormat, x, n, exponent).
  554. auto notation_sub_parts = partition_notation_sub_pattern(number_format, number, formatted_string, exponent);
  555. // ii. Append all elements of notationSubParts to result.
  556. result.extend(move(notation_sub_parts));
  557. }
  558. // d. Else if p is equal to "plusSign", then
  559. else if (part == "plusSign"sv) {
  560. // i. Let plusSignSymbol be the ILND String representing the plus sign.
  561. auto plus_sign_symbol = Unicode::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), "plusSign"sv).value_or("+"sv);
  562. // ii. Append a new Record { [[Type]]: "plusSign", [[Value]]: plusSignSymbol } as the last element of result.
  563. result.append({ "plusSign"sv, plus_sign_symbol });
  564. }
  565. // e. Else if p is equal to "minusSign", then
  566. else if (part == "minusSign"sv) {
  567. // i. Let minusSignSymbol be the ILND String representing the minus sign.
  568. auto minus_sign_symbol = Unicode::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), "minusSign"sv).value_or("-"sv);
  569. // ii. Append a new Record { [[Type]]: "minusSign", [[Value]]: minusSignSymbol } as the last element of result.
  570. result.append({ "minusSign"sv, minus_sign_symbol });
  571. }
  572. // f. Else if p is equal to "percentSign" and numberFormat.[[Style]] is "percent", then
  573. else if ((part == "percentSign"sv) && (number_format.style() == NumberFormat::Style::Percent)) {
  574. // i. Let percentSignSymbol be the ILND String representing the percent sign.
  575. auto percent_sign_symbol = Unicode::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), "percentSign"sv).value_or("%"sv);
  576. // ii. Append a new Record { [[Type]]: "percentSign", [[Value]]: percentSignSymbol } as the last element of result.
  577. result.append({ "percentSign"sv, percent_sign_symbol });
  578. }
  579. // g. Else if p is equal to "unitPrefix" and numberFormat.[[Style]] is "unit", then
  580. // h. Else if p is equal to "unitSuffix" and numberFormat.[[Style]] is "unit", then
  581. else if ((part.starts_with("unitIdentifier:"sv)) && (number_format.style() == NumberFormat::Style::Unit)) {
  582. // Note: Our implementation combines "unitPrefix" and "unitSuffix" into one field, "unitIdentifier".
  583. auto identifier_index = part.substring_view("unitIdentifier:"sv.length()).to_uint();
  584. VERIFY(identifier_index.has_value());
  585. // i. Let unit be numberFormat.[[Unit]].
  586. // ii. Let unitDisplay be numberFormat.[[UnitDisplay]].
  587. // iii. Let mu be an ILD String value representing unit before x in unitDisplay form, which may depend on x in languages having different plural forms.
  588. auto unit_identifier = found_pattern.identifiers[*identifier_index];
  589. // iv. Append a new Record { [[Type]]: "unit", [[Value]]: mu } as the last element of result.
  590. result.append({ "unit"sv, unit_identifier });
  591. }
  592. // i. Else if p is equal to "currencyCode" and numberFormat.[[Style]] is "currency", then
  593. // j. Else if p is equal to "currencyPrefix" and numberFormat.[[Style]] is "currency", then
  594. // k. Else if p is equal to "currencySuffix" and numberFormat.[[Style]] is "currency", then
  595. //
  596. // Note: Our implementation manipulates the format string to inject/remove spacing around the
  597. // currency code during GetNumberFormatPattern so that we do not have to do currency
  598. // display / plurality lookups more than once.
  599. else if ((part == "currency"sv) && (number_format.style() == NumberFormat::Style::Currency)) {
  600. result.append({ "currency"sv, number_format.resolve_currency_display() });
  601. }
  602. // l. Else,
  603. else {
  604. // i. Let unknown be an ILND String based on x and p.
  605. // ii. Append a new Record { [[Type]]: "unknown", [[Value]]: unknown } as the last element of result.
  606. // LibUnicode doesn't generate any "unknown" patterns.
  607. VERIFY_NOT_REACHED();
  608. }
  609. }
  610. // 9. Return result.
  611. return result;
  612. }
  613. static String replace_digits_for_number_format(NumberFormat& number_format, String formatted_string)
  614. {
  615. // https://tc39.es/ecma402/#table-numbering-system-digits
  616. static HashMap<StringView, AK::Array<u32, 10>> s_numbering_system_digits = {
  617. { "adlm"sv, { 0x1e950, 0x1e951, 0x1e952, 0x1e953, 0x1e954, 0x1e955, 0x1e956, 0x1e957, 0x1e958, 0x1e959 } },
  618. { "ahom"sv, { 0x11730, 0x11731, 0x11732, 0x11733, 0x11734, 0x11735, 0x11736, 0x11737, 0x11738, 0x11739 } },
  619. { "arab"sv, { 0x660, 0x661, 0x662, 0x663, 0x664, 0x665, 0x666, 0x667, 0x668, 0x669 } },
  620. { "arabext"sv, { 0x6f0, 0x6f1, 0x6f2, 0x6f3, 0x6f4, 0x6f5, 0x6f6, 0x6f7, 0x6f8, 0x6f9 } },
  621. { "bali"sv, { 0x1b50, 0x1b51, 0x1b52, 0x1b53, 0x1b54, 0x1b55, 0x1b56, 0x1b57, 0x1b58, 0x1b59 } },
  622. { "beng"sv, { 0x9e6, 0x9e7, 0x9e8, 0x9e9, 0x9ea, 0x9eb, 0x9ec, 0x9ed, 0x9ee, 0x9ef } },
  623. { "bhks"sv, { 0x11c50, 0x11c51, 0x11c52, 0x11c53, 0x11c54, 0x11c55, 0x11c56, 0x11c57, 0x11c58, 0x11c59 } },
  624. { "brah"sv, { 0x11066, 0x11067, 0x11068, 0x11069, 0x1106a, 0x1106b, 0x1106c, 0x1106d, 0x1106e, 0x1106f } },
  625. { "cakm"sv, { 0x11136, 0x11137, 0x11138, 0x11139, 0x1113a, 0x1113b, 0x1113c, 0x1113d, 0x1113e, 0x1113f } },
  626. { "cham"sv, { 0xaa50, 0xaa51, 0xaa52, 0xaa53, 0xaa54, 0xaa55, 0xaa56, 0xaa57, 0xaa58, 0xaa59 } },
  627. { "deva"sv, { 0x966, 0x967, 0x968, 0x969, 0x96a, 0x96b, 0x96c, 0x96d, 0x96e, 0x96f } },
  628. { "diak"sv, { 0x11950, 0x11951, 0x11952, 0x11953, 0x11954, 0x11955, 0x11956, 0x11957, 0x11958, 0x11959 } },
  629. { "fullwide"sv, { 0xff10, 0xff11, 0xff12, 0xff13, 0xff14, 0xff15, 0xff16, 0xff17, 0xff18, 0xff19 } },
  630. { "gong"sv, { 0x11da0, 0x11da1, 0x11da2, 0x11da3, 0x11da4, 0x11da5, 0x11da6, 0x11da7, 0x11da8, 0x11da9 } },
  631. { "gonm"sv, { 0x11d50, 0x11d51, 0x11d52, 0x11d53, 0x11d54, 0x11d55, 0x11d56, 0x11d57, 0x11d58, 0x11d59 } },
  632. { "gujr"sv, { 0xae6, 0xae7, 0xae8, 0xae9, 0xaea, 0xaeb, 0xaec, 0xaed, 0xaee, 0xaef } },
  633. { "guru"sv, { 0xa66, 0xa67, 0xa68, 0xa69, 0xa6a, 0xa6b, 0xa6c, 0xa6d, 0xa6e, 0xa6f } },
  634. { "hanidec"sv, { 0x3007, 0x4e00, 0x4e8c, 0x4e09, 0x56db, 0x4e94, 0x516d, 0x4e03, 0x516b, 0x4e5d } },
  635. { "hmng"sv, { 0x16b50, 0x16b51, 0x16b52, 0x16b53, 0x16b54, 0x16b55, 0x16b56, 0x16b57, 0x16b58, 0x16b59 } },
  636. { "hmnp"sv, { 0x1e140, 0x1e141, 0x1e142, 0x1e143, 0x1e144, 0x1e145, 0x1e146, 0x1e147, 0x1e148, 0x1e149 } },
  637. { "java"sv, { 0xa9d0, 0xa9d1, 0xa9d2, 0xa9d3, 0xa9d4, 0xa9d5, 0xa9d6, 0xa9d7, 0xa9d8, 0xa9d9 } },
  638. { "kali"sv, { 0xa900, 0xa901, 0xa902, 0xa903, 0xa904, 0xa905, 0xa906, 0xa907, 0xa908, 0xa909 } },
  639. { "khmr"sv, { 0x17e0, 0x17e1, 0x17e2, 0x17e3, 0x17e4, 0x17e5, 0x17e6, 0x17e7, 0x17e8, 0x17e9 } },
  640. { "knda"sv, { 0xce6, 0xce7, 0xce8, 0xce9, 0xcea, 0xceb, 0xcec, 0xced, 0xcee, 0xcef } },
  641. { "lana"sv, { 0x1a80, 0x1a81, 0x1a82, 0x1a83, 0x1a84, 0x1a85, 0x1a86, 0x1a87, 0x1a88, 0x1a89 } },
  642. { "lanatham"sv, { 0x1a90, 0x1a91, 0x1a92, 0x1a93, 0x1a94, 0x1a95, 0x1a96, 0x1a97, 0x1a98, 0x1a99 } },
  643. { "laoo"sv, { 0xed0, 0xed1, 0xed2, 0xed3, 0xed4, 0xed5, 0xed6, 0xed7, 0xed8, 0xed9 } },
  644. { "latn"sv, { 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39 } },
  645. { "lepc"sv, { 0x1c40, 0x1c41, 0x1c42, 0x1c43, 0x1c44, 0x1c45, 0x1c46, 0x1c47, 0x1c48, 0x1c49 } },
  646. { "limb"sv, { 0x1946, 0x1947, 0x1948, 0x1949, 0x194a, 0x194b, 0x194c, 0x194d, 0x194e, 0x194f } },
  647. { "mathbold"sv, { 0x1d7ce, 0x1d7cf, 0x1d7d0, 0x1d7d1, 0x1d7d2, 0x1d7d3, 0x1d7d4, 0x1d7d5, 0x1d7d6, 0x1d7d7 } },
  648. { "mathdbl"sv, { 0x1d7d8, 0x1d7d9, 0x1d7da, 0x1d7db, 0x1d7dc, 0x1d7dd, 0x1d7de, 0x1d7df, 0x1d7e0, 0x1d7e1 } },
  649. { "mathmono"sv, { 0x1d7f6, 0x1d7f7, 0x1d7f8, 0x1d7f9, 0x1d7fa, 0x1d7fb, 0x1d7fc, 0x1d7fd, 0x1d7fe, 0x1d7ff } },
  650. { "mathsanb"sv, { 0x1d7ec, 0x1d7ed, 0x1d7ee, 0x1d7ef, 0x1d7f0, 0x1d7f1, 0x1d7f2, 0x1d7f3, 0x1d7f4, 0x1d7f5 } },
  651. { "mathsans"sv, { 0x1d7e2, 0x1d7e3, 0x1d7e4, 0x1d7e5, 0x1d7e6, 0x1d7e7, 0x1d7e8, 0x1d7e9, 0x1d7ea, 0x1d7eb } },
  652. { "mlym"sv, { 0xd66, 0xd67, 0xd68, 0xd69, 0xd6a, 0xd6b, 0xd6c, 0xd6d, 0xd6e, 0xd6f } },
  653. { "modi"sv, { 0x11650, 0x11651, 0x11652, 0x11653, 0x11654, 0x11655, 0x11656, 0x11657, 0x11658, 0x11659 } },
  654. { "mong"sv, { 0x1810, 0x1811, 0x1812, 0x1813, 0x1814, 0x1815, 0x1816, 0x1817, 0x1818, 0x1819 } },
  655. { "mroo"sv, { 0x16a60, 0x16a61, 0x16a62, 0x16a63, 0x16a64, 0x16a65, 0x16a66, 0x16a67, 0x16a68, 0x16a69 } },
  656. { "mtei"sv, { 0xabf0, 0xabf1, 0xabf2, 0xabf3, 0xabf4, 0xabf5, 0xabf6, 0xabf7, 0xabf8, 0xabf9 } },
  657. { "mymr"sv, { 0x1040, 0x1041, 0x1042, 0x1043, 0x1044, 0x1045, 0x1046, 0x1047, 0x1048, 0x1049 } },
  658. { "mymrshan"sv, { 0x1090, 0x1091, 0x1092, 0x1093, 0x1094, 0x1095, 0x1096, 0x1097, 0x1098, 0x1099 } },
  659. { "mymrtlng"sv, { 0xa9f0, 0xa9f1, 0xa9f2, 0xa9f3, 0xa9f4, 0xa9f5, 0xa9f6, 0xa9f7, 0xa9f8, 0xa9f9 } },
  660. { "newa"sv, { 0x11450, 0x11451, 0x11452, 0x11453, 0x11454, 0x11455, 0x11456, 0x11457, 0x11458, 0x11459 } },
  661. { "nkoo"sv, { 0x7c0, 0x7c1, 0x7c2, 0x7c3, 0x7c4, 0x7c5, 0x7c6, 0x7c7, 0x7c8, 0x7c9 } },
  662. { "olck"sv, { 0x1c50, 0x1c51, 0x1c52, 0x1c53, 0x1c54, 0x1c55, 0x1c56, 0x1c57, 0x1c58, 0x1c59 } },
  663. { "orya"sv, { 0xb66, 0xb67, 0xb68, 0xb69, 0xb6a, 0xb6b, 0xb6c, 0xb6d, 0xb6e, 0xb6f } },
  664. { "osma"sv, { 0x104a0, 0x104a1, 0x104a2, 0x104a3, 0x104a4, 0x104a5, 0x104a6, 0x104a7, 0x104a8, 0x104a9 } },
  665. { "rohg"sv, { 0x10d30, 0x10d31, 0x10d32, 0x10d33, 0x10d34, 0x10d35, 0x10d36, 0x10d37, 0x10d38, 0x10d39 } },
  666. { "saur"sv, { 0xa8d0, 0xa8d1, 0xa8d2, 0xa8d3, 0xa8d4, 0xa8d5, 0xa8d6, 0xa8d7, 0xa8d8, 0xa8d9 } },
  667. { "segment"sv, { 0x1fbf0, 0x1fbf1, 0x1fbf2, 0x1fbf3, 0x1fbf4, 0x1fbf5, 0x1fbf6, 0x1fbf7, 0x1fbf8, 0x1fbf9 } },
  668. { "shrd"sv, { 0x111d0, 0x111d1, 0x111d2, 0x111d3, 0x111d4, 0x111d5, 0x111d6, 0x111d7, 0x111d8, 0x111d9 } },
  669. { "sind"sv, { 0x112f0, 0x112f1, 0x112f2, 0x112f3, 0x112f4, 0x112f5, 0x112f6, 0x112f7, 0x112f8, 0x112f9 } },
  670. { "sinh"sv, { 0xde6, 0xde7, 0xde8, 0xde9, 0xdea, 0xdeb, 0xdec, 0xded, 0xdee, 0xdef } },
  671. { "sora"sv, { 0x110f0, 0x110f1, 0x110f2, 0x110f3, 0x110f4, 0x110f5, 0x110f6, 0x110f7, 0x110f8, 0x110f9 } },
  672. { "sund"sv, { 0x1bb0, 0x1bb1, 0x1bb2, 0x1bb3, 0x1bb4, 0x1bb5, 0x1bb6, 0x1bb7, 0x1bb8, 0x1bb9 } },
  673. { "takr"sv, { 0x116c0, 0x116c1, 0x116c2, 0x116c3, 0x116c4, 0x116c5, 0x116c6, 0x116c7, 0x116c8, 0x116c9 } },
  674. { "talu"sv, { 0x19d0, 0x19d1, 0x19d2, 0x19d3, 0x19d4, 0x19d5, 0x19d6, 0x19d7, 0x19d8, 0x19d9 } },
  675. { "tamldec"sv, { 0xbe6, 0xbe7, 0xbe8, 0xbe9, 0xbea, 0xbeb, 0xbec, 0xbed, 0xbee, 0xbef } },
  676. { "telu"sv, { 0xc66, 0xc67, 0xc68, 0xc69, 0xc6a, 0xc6b, 0xc6c, 0xc6d, 0xc6e, 0xc6f } },
  677. { "thai"sv, { 0xe50, 0xe51, 0xe52, 0xe53, 0xe54, 0xe55, 0xe56, 0xe57, 0xe58, 0xe59 } },
  678. { "tibt"sv, { 0xf20, 0xf21, 0xf22, 0xf23, 0xf24, 0xf25, 0xf26, 0xf27, 0xf28, 0xf29 } },
  679. { "tirh"sv, { 0x114d0, 0x114d1, 0x114d2, 0x114d3, 0x114d4, 0x114d5, 0x114d6, 0x114d7, 0x114d8, 0x114d9 } },
  680. { "vaii"sv, { 0xa620, 0xa621, 0xa622, 0xa623, 0xa624, 0xa625, 0xa626, 0xa627, 0xa628, 0xa629 } },
  681. { "wara"sv, { 0x118e0, 0x118e1, 0x118e2, 0x118e3, 0x118e4, 0x118e5, 0x118e6, 0x118e7, 0x118e8, 0x118e9 } },
  682. { "wcho"sv, { 0x1e2f0, 0x1e2f1, 0x1e2f2, 0x1e2f3, 0x1e2f4, 0x1e2f5, 0x1e2f6, 0x1e2f7, 0x1e2f8, 0x1e2f9 } },
  683. };
  684. auto digits = s_numbering_system_digits.get(number_format.numbering_system());
  685. if (!digits.has_value())
  686. digits = s_numbering_system_digits.get("latn"sv);
  687. VERIFY(digits.has_value());
  688. StringBuilder builder;
  689. for (auto& ch : formatted_string) {
  690. if (is_ascii_digit(ch)) {
  691. u32 digit = digits->at(parse_ascii_digit(ch));
  692. builder.append_code_point(digit);
  693. } else {
  694. builder.append(ch);
  695. }
  696. }
  697. return builder.build();
  698. }
  699. static Vector<StringView> separate_integer_into_groups(Unicode::NumberGroupings const& grouping_sizes, StringView integer)
  700. {
  701. Utf8View utf8_integer { integer };
  702. Vector<StringView> groups;
  703. auto add_group = [&](size_t index, size_t length) {
  704. groups.prepend(utf8_integer.unicode_substring_view(index, length).as_string());
  705. };
  706. if (utf8_integer.length() > grouping_sizes.primary_grouping_size) {
  707. size_t index = utf8_integer.length() - grouping_sizes.primary_grouping_size;
  708. add_group(index, grouping_sizes.primary_grouping_size);
  709. while (index > grouping_sizes.secondary_grouping_size) {
  710. index -= grouping_sizes.secondary_grouping_size;
  711. add_group(index, grouping_sizes.secondary_grouping_size);
  712. }
  713. if (index > 0)
  714. add_group(0, index);
  715. } else {
  716. groups.append(integer);
  717. }
  718. return groups;
  719. }
  720. // 15.1.7 PartitionNotationSubPattern ( numberFormat, x, n, exponent ), https://tc39.es/ecma402/#sec-partitionnotationsubpattern
  721. Vector<PatternPartition> partition_notation_sub_pattern(NumberFormat& number_format, double number, String formatted_string, int exponent)
  722. {
  723. // 1. Let result be a new empty List.
  724. Vector<PatternPartition> result;
  725. auto grouping_sizes = Unicode::get_number_system_groupings(number_format.data_locale(), number_format.numbering_system());
  726. if (!grouping_sizes.has_value())
  727. return {};
  728. // 2. If x is NaN, then
  729. if (Value(number).is_nan()) {
  730. // a. Append a new Record { [[Type]]: "nan", [[Value]]: n } as the last element of result.
  731. result.append({ "nan"sv, move(formatted_string) });
  732. }
  733. // 3. Else if x is a non-finite Number, then
  734. else if (!Value(number).is_finite_number()) {
  735. // a. Append a new Record { [[Type]]: "infinity", [[Value]]: n } as the last element of result.
  736. result.append({ "infinity"sv, move(formatted_string) });
  737. }
  738. // 4. Else,
  739. else {
  740. // a. Let notationSubPattern be GetNotationSubPattern(numberFormat, exponent).
  741. auto notation_sub_pattern = get_notation_sub_pattern(number_format, exponent);
  742. if (!notation_sub_pattern.has_value())
  743. return {};
  744. // b. Let patternParts be PartitionPattern(notationSubPattern).
  745. auto pattern_parts = partition_pattern(*notation_sub_pattern);
  746. // c. For each Record { [[Type]], [[Value]] } patternPart of patternParts, do
  747. for (auto& pattern_part : pattern_parts) {
  748. // i. Let p be patternPart.[[Type]].
  749. auto part = pattern_part.type;
  750. // ii. If p is "literal", then
  751. if (part == "literal"sv) {
  752. // 1. Append a new Record { [[Type]]: "literal", [[Value]]: patternPart.[[Value]] } as the last element of result.
  753. result.append({ "literal"sv, move(pattern_part.value) });
  754. }
  755. // iii. Else if p is equal to "number", then
  756. else if (part == "number"sv) {
  757. // 1. If the numberFormat.[[NumberingSystem]] matches one of the values in the "Numbering System" column of Table 10 below, then
  758. // a. Let digits be a List whose 10 String valued elements are the UTF-16 string representations of the 10 digits specified in the "Digits" column of the matching row in Table 10.
  759. // b. Replace each digit in n with the value of digits[digit].
  760. // 2. Else use an implementation dependent algorithm to map n to the appropriate representation of n in the given numbering system.
  761. formatted_string = replace_digits_for_number_format(number_format, move(formatted_string));
  762. // 3. Let decimalSepIndex be ! StringIndexOf(n, ".", 0).
  763. auto decimal_sep_index = formatted_string.find('.');
  764. StringView integer;
  765. Optional<StringView> fraction;
  766. // 4. If decimalSepIndex > 0, then
  767. if (decimal_sep_index.has_value() && (*decimal_sep_index > 0)) {
  768. // a. Let integer be the substring of n from position 0, inclusive, to position decimalSepIndex, exclusive.
  769. integer = formatted_string.substring_view(0, *decimal_sep_index);
  770. // b. Let fraction be the substring of n from position decimalSepIndex, exclusive, to the end of n.
  771. fraction = formatted_string.substring_view(*decimal_sep_index + 1);
  772. }
  773. // 5. Else,
  774. else {
  775. // a. Let integer be n.
  776. integer = formatted_string;
  777. // b. Let fraction be undefined.
  778. }
  779. bool use_grouping = number_format.use_grouping();
  780. // FIXME: The spec doesn't indicate this, but grouping should be disabled for numbers less than 10,000 when the notation is compact.
  781. // This is addressed in Intl.NumberFormat V3 with the "min2" [[UseGrouping]] option. However, test262 explicitly expects this
  782. // behavior in the "de-DE" locale tests, because this is how ICU (and therefore V8, SpiderMoney, etc.) has always behaved.
  783. //
  784. // So, in locales "de-*", we must have:
  785. // Intl.NumberFormat("de", {notation: "compact"}).format(1234) === "1234"
  786. // Intl.NumberFormat("de", {notation: "compact"}).format(12345) === "12.345"
  787. // Intl.NumberFormat("de").format(1234) === "1.234"
  788. // Intl.NumberFormat("de").format(12345) === "12.345"
  789. //
  790. // See: https://github.com/tc39/proposal-intl-numberformat-v3/issues/3
  791. if (number_format.has_compact_format())
  792. use_grouping = number >= 10'000;
  793. // 6. If the numberFormat.[[UseGrouping]] is true, then
  794. if (use_grouping) {
  795. // a. Let groupSepSymbol be the implementation-, locale-, and numbering system-dependent (ILND) String representing the grouping separator.
  796. auto group_sep_symbol = Unicode::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), "group"sv).value_or(","sv);
  797. // b. Let groups be a List whose elements are, in left to right order, the substrings defined by ILND set of locations within the integer.
  798. auto groups = separate_integer_into_groups(*grouping_sizes, integer);
  799. // c. Assert: The number of elements in groups List is greater than 0.
  800. VERIFY(!groups.is_empty());
  801. // d. Repeat, while groups List is not empty,
  802. while (!groups.is_empty()) {
  803. // i. Remove the first element from groups and let integerGroup be the value of that element.
  804. auto integer_group = groups.take_first();
  805. // ii. Append a new Record { [[Type]]: "integer", [[Value]]: integerGroup } as the last element of result.
  806. result.append({ "integer"sv, integer_group });
  807. // iii. If groups List is not empty, then
  808. if (!groups.is_empty()) {
  809. // i. Append a new Record { [[Type]]: "group", [[Value]]: groupSepSymbol } as the last element of result.
  810. result.append({ "group"sv, group_sep_symbol });
  811. }
  812. }
  813. }
  814. // 7. Else,
  815. else {
  816. // a. Append a new Record { [[Type]]: "integer", [[Value]]: integer } as the last element of result.
  817. result.append({ "integer"sv, integer });
  818. }
  819. // 8. If fraction is not undefined, then
  820. if (fraction.has_value()) {
  821. // a. Let decimalSepSymbol be the ILND String representing the decimal separator.
  822. auto decimal_sep_symbol = Unicode::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), "decimal"sv).value_or("."sv);
  823. // b. Append a new Record { [[Type]]: "decimal", [[Value]]: decimalSepSymbol } as the last element of result.
  824. result.append({ "decimal"sv, decimal_sep_symbol });
  825. // c. Append a new Record { [[Type]]: "fraction", [[Value]]: fraction } as the last element of result.
  826. result.append({ "fraction"sv, fraction.release_value() });
  827. }
  828. }
  829. // iv. Else if p is equal to "compactSymbol", then
  830. // v. Else if p is equal to "compactName", then
  831. else if (part.starts_with("compactIdentifier:"sv)) {
  832. // Note: Our implementation combines "compactSymbol" and "compactName" into one field, "compactIdentifier".
  833. auto identifier_index = part.substring_view("compactIdentifier:"sv.length()).to_uint();
  834. VERIFY(identifier_index.has_value());
  835. // 1. Let compactSymbol be an ILD string representing exponent in short form, which may depend on x in languages having different plural forms. The implementation must be able to provide this string, or else the pattern would not have a "{compactSymbol}" placeholder.
  836. auto compact_identifier = number_format.compact_format().identifiers[*identifier_index];
  837. // 2. Append a new Record { [[Type]]: "compact", [[Value]]: compactSymbol } as the last element of result.
  838. result.append({ "compact"sv, compact_identifier });
  839. }
  840. // vi. Else if p is equal to "scientificSeparator", then
  841. else if (part == "scientificSeparator"sv) {
  842. // 1. Let scientificSeparator be the ILND String representing the exponent separator.
  843. auto scientific_separator = Unicode::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), "exponential"sv).value_or("E"sv);
  844. // 2. Append a new Record { [[Type]]: "exponentSeparator", [[Value]]: scientificSeparator } as the last element of result.
  845. result.append({ "exponentSeparator"sv, scientific_separator });
  846. }
  847. // vii. Else if p is equal to "scientificExponent", then
  848. else if (part == "scientificExponent"sv) {
  849. // 1. If exponent < 0, then
  850. if (exponent < 0) {
  851. // a. Let minusSignSymbol be the ILND String representing the minus sign.
  852. auto minus_sign_symbol = Unicode::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), "minusSign"sv).value_or("-"sv);
  853. // b. Append a new Record { [[Type]]: "exponentMinusSign", [[Value]]: minusSignSymbol } as the last element of result.
  854. result.append({ "exponentMinusSign"sv, minus_sign_symbol });
  855. // c. Let exponent be -exponent.
  856. exponent *= -1;
  857. }
  858. // 2. Let exponentResult be ToRawFixed(exponent, 1, 0, 0).
  859. // Note: See the implementation of ToRawFixed for why we do not pass the 1.
  860. auto exponent_result = to_raw_fixed(exponent, 0, 0);
  861. // FIXME: The spec does not say to do this, but all of major engines perform this replacement.
  862. // Without this, formatting with non-Latin numbering systems will produce non-localized results.
  863. exponent_result.formatted_string = replace_digits_for_number_format(number_format, move(exponent_result.formatted_string));
  864. // 3. Append a new Record { [[Type]]: "exponentInteger", [[Value]]: exponentResult.[[FormattedString]] } as the last element of result.
  865. result.append({ "exponentInteger"sv, move(exponent_result.formatted_string) });
  866. }
  867. // viii. Else,
  868. else {
  869. // 1. Let unknown be an ILND String based on x and p.
  870. // 2. Append a new Record { [[Type]]: "unknown", [[Value]]: unknown } as the last element of result.
  871. // LibUnicode doesn't generate any "unknown" patterns.
  872. VERIFY_NOT_REACHED();
  873. }
  874. }
  875. }
  876. // 5. Return result.
  877. return result;
  878. }
  879. // 15.1.8 FormatNumeric ( numberFormat, x ), https://tc39.es/ecma402/#sec-formatnumber
  880. String format_numeric(NumberFormat& number_format, double number)
  881. {
  882. // 1. Let parts be ? PartitionNumberPattern(numberFormat, x).
  883. // Note: Our implementation of PartitionNumberPattern does not throw.
  884. auto parts = partition_number_pattern(number_format, number);
  885. // 2. Let result be the empty String.
  886. StringBuilder result;
  887. // 3. For each Record { [[Type]], [[Value]] } part in parts, do
  888. for (auto& part : parts) {
  889. // a. Set result to the string-concatenation of result and part.[[Value]].
  890. result.append(move(part.value));
  891. }
  892. // 4. Return result.
  893. return result.build();
  894. }
  895. // 15.1.9 FormatNumericToParts ( numberFormat, x ), https://tc39.es/ecma402/#sec-formatnumbertoparts
  896. Array* format_numeric_to_parts(GlobalObject& global_object, NumberFormat& number_format, double number)
  897. {
  898. auto& vm = global_object.vm();
  899. // 1. Let parts be ? PartitionNumberPattern(numberFormat, x).
  900. // Note: Our implementation of PartitionNumberPattern does not throw.
  901. auto parts = partition_number_pattern(number_format, number);
  902. // 2. Let result be ArrayCreate(0).
  903. auto* result = MUST(Array::create(global_object, 0));
  904. // 3. Let n be 0.
  905. size_t n = 0;
  906. // 4. For each Record { [[Type]], [[Value]] } part in parts, do
  907. for (auto& part : parts) {
  908. // a. Let O be OrdinaryObjectCreate(%Object.prototype%).
  909. auto* object = Object::create(global_object, global_object.object_prototype());
  910. // b. Perform ! CreateDataPropertyOrThrow(O, "type", part.[[Type]]).
  911. MUST(object->create_data_property_or_throw(vm.names.type, js_string(vm, part.type)));
  912. // c. Perform ! CreateDataPropertyOrThrow(O, "value", part.[[Value]]).
  913. MUST(object->create_data_property_or_throw(vm.names.value, js_string(vm, move(part.value))));
  914. // d. Perform ! CreateDataPropertyOrThrow(result, ! ToString(n), O).
  915. MUST(result->create_data_property_or_throw(n, object));
  916. // e. Increment n by 1.
  917. ++n;
  918. }
  919. // 5. Return result.
  920. return result;
  921. }
  922. static String cut_trailing_zeroes(StringView string, int cut)
  923. {
  924. // These steps are exactly the same between ToRawPrecision and ToRawFixed.
  925. // Repeat, while cut > 0 and the last character of m is "0",
  926. while ((cut > 0) && string.ends_with('0')) {
  927. // Remove the last character from m.
  928. string = string.substring_view(0, string.length() - 1);
  929. // Decrease cut by 1.
  930. --cut;
  931. }
  932. // If the last character of m is ".", then
  933. if (string.ends_with('.')) {
  934. // Remove the last character from m.
  935. string = string.substring_view(0, string.length() - 1);
  936. }
  937. return string.to_string();
  938. }
  939. // 15.1.10 ToRawPrecision ( x, minPrecision, maxPrecision ), https://tc39.es/ecma402/#sec-torawprecision
  940. RawFormatResult to_raw_precision(double number, int min_precision, int max_precision)
  941. {
  942. RawFormatResult result {};
  943. // 1. Let p be maxPrecision.
  944. int precision = max_precision;
  945. int exponent = 0;
  946. // 2. If x = 0, then
  947. if (number == 0.0) {
  948. // a. Let m be the String consisting of p occurrences of the character "0".
  949. result.formatted_string = String::repeated('0', precision);
  950. // b. Let e be 0.
  951. exponent = 0;
  952. // c. Let xFinal be 0.
  953. result.rounded_number = 0;
  954. }
  955. // 3. Else,
  956. else {
  957. // FIXME: The result of these steps isn't entirely accurate for large values of 'p' (which
  958. // defaults to 21, resulting in numbers on the order of 10^21). Either AK::format or
  959. // our Number::toString AO (double_to_string in Value.cpp) will need to be improved
  960. // to produce more accurate results.
  961. // a. Let e be the base 10 logarithm of x rounded down to the nearest integer.
  962. exponent = log10floor(number);
  963. double power = pow(10, exponent - precision + 1);
  964. // b. Let n be an integer such that 10^(p–1) ≤ n < 10^p and for which the exact mathematical value of n × 10^(e–p+1) – x
  965. // is as close to zero as possible. If there is more than one such n, pick the one for which n × 10^(e–p+1) is larger.
  966. double n = round(number / power);
  967. // c. Let m be the String consisting of the digits of the decimal representation of n (in order, with no leading zeroes).
  968. result.formatted_string = Value(n).to_string_without_side_effects();
  969. // d. Let xFinal be n × 10^(e–p+1).
  970. result.rounded_number = n * power;
  971. }
  972. // 4. If e ≥ p–1, then
  973. if (exponent >= (precision - 1)) {
  974. // a. Let m be the string-concatenation of m and e–p+1 occurrences of the character "0".
  975. result.formatted_string = String::formatted(
  976. "{}{}",
  977. result.formatted_string,
  978. String::repeated('0', exponent - precision + 1));
  979. // b. Let int be e+1.
  980. result.digits = exponent + 1;
  981. }
  982. // 5. Else if e ≥ 0, then
  983. else if (exponent >= 0) {
  984. // a. Let m be the string-concatenation of the first e+1 characters of m, the character ".", and the remaining p–(e+1) characters of m.
  985. result.formatted_string = String::formatted(
  986. "{}.{}",
  987. result.formatted_string.substring_view(0, exponent + 1),
  988. result.formatted_string.substring_view(exponent + 1));
  989. // b. Let int be e+1.
  990. result.digits = exponent + 1;
  991. }
  992. // 6. Else,
  993. else {
  994. // a. Assert: e < 0.
  995. // b. Let m be the string-concatenation of the String value "0.", –(e+1) occurrences of the character "0", and m.
  996. result.formatted_string = String::formatted(
  997. "0.{}{}",
  998. String::repeated('0', -1 * (exponent + 1)),
  999. result.formatted_string);
  1000. // c. Let int be 1.
  1001. result.digits = 1;
  1002. }
  1003. // 7. If m contains the character ".", and maxPrecision > minPrecision, then
  1004. if (result.formatted_string.contains('.') && (max_precision > min_precision)) {
  1005. // a. Let cut be maxPrecision – minPrecision.
  1006. int cut = max_precision - min_precision;
  1007. result.formatted_string = cut_trailing_zeroes(result.formatted_string, cut);
  1008. }
  1009. // 8. Return the Record { [[FormattedString]]: m, [[RoundedNumber]]: xFinal, [[IntegerDigitsCount]]: int }.
  1010. return result;
  1011. }
  1012. // 15.1.11 ToRawFixed ( x, minInteger, minFraction, maxFraction ), https://tc39.es/ecma402/#sec-torawfixed
  1013. // NOTE: The spec has a mistake here. The minInteger parameter is unused and is not provided by FormatNumericToString.
  1014. RawFormatResult to_raw_fixed(double number, int min_fraction, int max_fraction)
  1015. {
  1016. RawFormatResult result {};
  1017. // 1. Let f be maxFraction.
  1018. int fraction = max_fraction;
  1019. double power = pow(10, fraction);
  1020. // 2. Let n be an integer for which the exact mathematical value of n / 10^f – x is as close to zero as possible. If there are two such n, pick the larger n.
  1021. double n = round(number * power);
  1022. // 3. Let xFinal be n / 10^f.
  1023. result.rounded_number = n / power;
  1024. // 4. If n = 0, let m be the String "0". Otherwise, let m be the String consisting of the digits of the decimal representation of n (in order, with no leading zeroes).
  1025. result.formatted_string = n == 0.0 ? String("0"sv) : Value(n).to_string_without_side_effects();
  1026. // 5. If f ≠ 0, then
  1027. if (fraction != 0) {
  1028. // a. Let k be the number of characters in m.
  1029. auto decimals = result.formatted_string.length();
  1030. // b. If k ≤ f, then
  1031. if (decimals <= static_cast<size_t>(fraction)) {
  1032. // i. Let z be the String value consisting of f+1–k occurrences of the character "0".
  1033. auto zeroes = String::repeated('0', fraction + 1 - decimals);
  1034. // ii. Let m be the string-concatenation of z and m.
  1035. result.formatted_string = String::formatted("{}{}", zeroes, result.formatted_string);
  1036. // iii. Let k be f+1.
  1037. decimals = fraction + 1;
  1038. }
  1039. // c. Let a be the first k–f characters of m, and let b be the remaining f characters of m.
  1040. auto a = result.formatted_string.substring_view(0, decimals - fraction);
  1041. auto b = result.formatted_string.substring_view(decimals - fraction, fraction);
  1042. // d. Let m be the string-concatenation of a, ".", and b.
  1043. result.formatted_string = String::formatted("{}.{}", a, b);
  1044. // e. Let int be the number of characters in a.
  1045. result.digits = a.length();
  1046. }
  1047. // 6. Else, let int be the number of characters in m.
  1048. else {
  1049. result.digits = result.formatted_string.length();
  1050. }
  1051. // 7. Let cut be maxFraction – minFraction.
  1052. int cut = max_fraction - min_fraction;
  1053. result.formatted_string = cut_trailing_zeroes(result.formatted_string, cut);
  1054. // 10. Return the Record { [[FormattedString]]: m, [[RoundedNumber]]: xFinal, [[IntegerDigitsCount]]: int }.
  1055. return result;
  1056. }
  1057. // 15.1.13 SetNumberFormatUnitOptions ( intlObj, options ), https://tc39.es/ecma402/#sec-setnumberformatunitoptions
  1058. ThrowCompletionOr<void> set_number_format_unit_options(GlobalObject& global_object, NumberFormat& intl_object, Object const& options)
  1059. {
  1060. auto& vm = global_object.vm();
  1061. // 1. Assert: Type(intlObj) is Object.
  1062. // 2. Assert: Type(options) is Object.
  1063. // 3. Let style be ? GetOption(options, "style", "string", « "decimal", "percent", "currency", "unit" », "decimal").
  1064. auto style = TRY(get_option(global_object, options, vm.names.style, Value::Type::String, { "decimal"sv, "percent"sv, "currency"sv, "unit"sv }, "decimal"sv));
  1065. // 4. Set intlObj.[[Style]] to style.
  1066. intl_object.set_style(style.as_string().string());
  1067. // 5. Let currency be ? GetOption(options, "currency", "string", undefined, undefined).
  1068. auto currency = TRY(get_option(global_object, options, vm.names.currency, Value::Type::String, {}, Empty {}));
  1069. // 6. If currency is undefined, then
  1070. if (currency.is_undefined()) {
  1071. // a. If style is "currency", throw a TypeError exception.
  1072. if (intl_object.style() == NumberFormat::Style::Currency)
  1073. return vm.throw_completion<TypeError>(global_object, ErrorType::IntlOptionUndefined, "currency"sv, "style"sv, style);
  1074. }
  1075. // 7. Else,
  1076. // a. If the result of IsWellFormedCurrencyCode(currency) is false, throw a RangeError exception.
  1077. else if (!is_well_formed_currency_code(currency.as_string().string()))
  1078. return vm.throw_completion<RangeError>(global_object, ErrorType::OptionIsNotValidValue, currency, "currency"sv);
  1079. // 8. Let currencyDisplay be ? GetOption(options, "currencyDisplay", "string", « "code", "symbol", "narrowSymbol", "name" », "symbol").
  1080. auto currency_display = TRY(get_option(global_object, options, vm.names.currencyDisplay, Value::Type::String, { "code"sv, "symbol"sv, "narrowSymbol"sv, "name"sv }, "symbol"sv));
  1081. // 9. Let currencySign be ? GetOption(options, "currencySign", "string", « "standard", "accounting" », "standard").
  1082. auto currency_sign = TRY(get_option(global_object, options, vm.names.currencySign, Value::Type::String, { "standard"sv, "accounting"sv }, "standard"sv));
  1083. // 10. Let unit be ? GetOption(options, "unit", "string", undefined, undefined).
  1084. auto unit = TRY(get_option(global_object, options, vm.names.unit, Value::Type::String, {}, Empty {}));
  1085. // 11. If unit is undefined, then
  1086. if (unit.is_undefined()) {
  1087. // a. If style is "unit", throw a TypeError exception.
  1088. if (intl_object.style() == NumberFormat::Style::Unit)
  1089. return vm.throw_completion<TypeError>(global_object, ErrorType::IntlOptionUndefined, "unit"sv, "style"sv, style);
  1090. }
  1091. // 12. Else,
  1092. // a. If the result of IsWellFormedUnitIdentifier(unit) is false, throw a RangeError exception.
  1093. else if (!is_well_formed_unit_identifier(unit.as_string().string()))
  1094. return vm.throw_completion<RangeError>(global_object, ErrorType::OptionIsNotValidValue, unit, "unit"sv);
  1095. // 13. Let unitDisplay be ? GetOption(options, "unitDisplay", "string", « "short", "narrow", "long" », "short").
  1096. auto unit_display = TRY(get_option(global_object, options, vm.names.unitDisplay, Value::Type::String, { "short"sv, "narrow"sv, "long"sv }, "short"sv));
  1097. // 14. If style is "currency", then
  1098. if (intl_object.style() == NumberFormat::Style::Currency) {
  1099. // a. Let currency be the result of converting currency to upper case as specified in 6.1.
  1100. // b. Set intlObj.[[Currency]] to currency.
  1101. intl_object.set_currency(currency.as_string().string().to_uppercase());
  1102. // c. Set intlObj.[[CurrencyDisplay]] to currencyDisplay.
  1103. intl_object.set_currency_display(currency_display.as_string().string());
  1104. // d. Set intlObj.[[CurrencySign]] to currencySign.
  1105. intl_object.set_currency_sign(currency_sign.as_string().string());
  1106. }
  1107. // 15. If style is "unit", then
  1108. if (intl_object.style() == NumberFormat::Style::Unit) {
  1109. // a. Set intlObj.[[Unit]] to unit.
  1110. intl_object.set_unit(unit.as_string().string());
  1111. // b. Set intlObj.[[UnitDisplay]] to unitDisplay.
  1112. intl_object.set_unit_display(unit_display.as_string().string());
  1113. }
  1114. return {};
  1115. }
  1116. // 15.1.14 GetNumberFormatPattern ( numberFormat, x ), https://tc39.es/ecma402/#sec-getnumberformatpattern
  1117. Optional<Variant<StringView, String>> get_number_format_pattern(NumberFormat& number_format, double number, Unicode::NumberFormat& found_pattern)
  1118. {
  1119. // 1. Let localeData be %NumberFormat%.[[LocaleData]].
  1120. // 2. Let dataLocale be numberFormat.[[DataLocale]].
  1121. // 3. Let dataLocaleData be localeData.[[<dataLocale>]].
  1122. // 4. Let patterns be dataLocaleData.[[patterns]].
  1123. // 5. Assert: patterns is a Record (see 15.3.3).
  1124. Optional<Unicode::NumberFormat> patterns;
  1125. // 6. Let style be numberFormat.[[Style]].
  1126. switch (number_format.style()) {
  1127. // 7. If style is "percent", then
  1128. case NumberFormat::Style::Percent:
  1129. // a. Let patterns be patterns.[[percent]].
  1130. patterns = Unicode::get_standard_number_system_format(number_format.data_locale(), number_format.numbering_system(), Unicode::StandardNumberFormatType::Percent);
  1131. break;
  1132. // 8. Else if style is "unit", then
  1133. case NumberFormat::Style::Unit: {
  1134. // a. Let unit be numberFormat.[[Unit]].
  1135. // b. Let unitDisplay be numberFormat.[[UnitDisplay]].
  1136. // c. Let patterns be patterns.[[unit]].
  1137. // d. If patterns doesn't have a field [[<unit>]], then
  1138. // i. Let unit be "fallback".
  1139. // e. Let patterns be patterns.[[<unit>]].
  1140. // f. Let patterns be patterns.[[<unitDisplay>]].
  1141. Vector<Unicode::NumberFormat> formats;
  1142. switch (number_format.unit_display()) {
  1143. case NumberFormat::UnitDisplay::Long:
  1144. formats = Unicode::get_unit_formats(number_format.data_locale(), number_format.unit(), Unicode::Style::Long);
  1145. break;
  1146. case NumberFormat::UnitDisplay::Short:
  1147. formats = Unicode::get_unit_formats(number_format.data_locale(), number_format.unit(), Unicode::Style::Short);
  1148. break;
  1149. case NumberFormat::UnitDisplay::Narrow:
  1150. formats = Unicode::get_unit_formats(number_format.data_locale(), number_format.unit(), Unicode::Style::Narrow);
  1151. break;
  1152. }
  1153. patterns = Unicode::select_pattern_with_plurality(formats, number);
  1154. break;
  1155. }
  1156. // 9. Else if style is "currency", then
  1157. case NumberFormat::Style::Currency:
  1158. // a. Let currency be numberFormat.[[Currency]].
  1159. // b. Let currencyDisplay be numberFormat.[[CurrencyDisplay]].
  1160. // c. Let currencySign be numberFormat.[[CurrencySign]].
  1161. // d. Let patterns be patterns.[[currency]].
  1162. // e. If patterns doesn't have a field [[<currency>]], then
  1163. // i. Let currency be "fallback".
  1164. // f. Let patterns be patterns.[[<currency>]].
  1165. // g. Let patterns be patterns.[[<currencyDisplay>]].
  1166. // h. Let patterns be patterns.[[<currencySign>]].
  1167. // Handling of other [[CurrencyDisplay]] options will occur after [[SignDisplay]].
  1168. if (number_format.currency_display() == NumberFormat::CurrencyDisplay::Name) {
  1169. auto formats = Unicode::get_compact_number_system_formats(number_format.data_locale(), number_format.numbering_system(), Unicode::CompactNumberFormatType::CurrencyUnit);
  1170. auto maybe_patterns = Unicode::select_pattern_with_plurality(formats, number);
  1171. if (maybe_patterns.has_value()) {
  1172. patterns = maybe_patterns.release_value();
  1173. break;
  1174. }
  1175. }
  1176. switch (number_format.currency_sign()) {
  1177. case NumberFormat::CurrencySign::Standard:
  1178. patterns = Unicode::get_standard_number_system_format(number_format.data_locale(), number_format.numbering_system(), Unicode::StandardNumberFormatType::Currency);
  1179. break;
  1180. case NumberFormat::CurrencySign::Accounting:
  1181. patterns = Unicode::get_standard_number_system_format(number_format.data_locale(), number_format.numbering_system(), Unicode::StandardNumberFormatType::Accounting);
  1182. break;
  1183. }
  1184. break;
  1185. // 10. Else,
  1186. case NumberFormat::Style::Decimal:
  1187. // a. Assert: style is "decimal".
  1188. // b. Let patterns be patterns.[[decimal]].
  1189. patterns = Unicode::get_standard_number_system_format(number_format.data_locale(), number_format.numbering_system(), Unicode::StandardNumberFormatType::Decimal);
  1190. break;
  1191. default:
  1192. VERIFY_NOT_REACHED();
  1193. }
  1194. if (!patterns.has_value())
  1195. return {};
  1196. StringView pattern;
  1197. Value number_value(number);
  1198. bool is_positive_zero = number_value.is_positive_zero();
  1199. bool is_negative_zero = number_value.is_negative_zero();
  1200. bool is_nan = number_value.is_nan();
  1201. // 11. Let signDisplay be numberFormat.[[SignDisplay]].
  1202. switch (number_format.sign_display()) {
  1203. // 12. If signDisplay is "never", then
  1204. case NumberFormat::SignDisplay::Never:
  1205. // a. Let pattern be patterns.[[zeroPattern]].
  1206. pattern = patterns->zero_format;
  1207. break;
  1208. // 13. Else if signDisplay is "auto", then
  1209. case NumberFormat::SignDisplay::Auto:
  1210. // a. If x is 0 or x > 0 or x is NaN, then
  1211. if (is_positive_zero || (number > 0) || is_nan) {
  1212. // i. Let pattern be patterns.[[zeroPattern]].
  1213. pattern = patterns->zero_format;
  1214. }
  1215. // b. Else,
  1216. else {
  1217. // i. Let pattern be patterns.[[negativePattern]].
  1218. pattern = patterns->negative_format;
  1219. }
  1220. break;
  1221. // 14. Else if signDisplay is "always", then
  1222. case NumberFormat::SignDisplay::Always:
  1223. // a. If x is 0 or x > 0 or x is NaN, then
  1224. if (is_positive_zero || (number > 0) || is_nan) {
  1225. // i. Let pattern be patterns.[[positivePattern]].
  1226. pattern = patterns->positive_format;
  1227. }
  1228. // b. Else,
  1229. else {
  1230. // i. Let pattern be patterns.[[negativePattern]].
  1231. pattern = patterns->negative_format;
  1232. }
  1233. break;
  1234. // 15. Else,
  1235. case NumberFormat::SignDisplay::ExceptZero:
  1236. // a. Assert: signDisplay is "exceptZero".
  1237. // b. If x is 0 or x is -0 or x is NaN, then
  1238. if (is_positive_zero || is_negative_zero || is_nan) {
  1239. // i. Let pattern be patterns.[[zeroPattern]].
  1240. pattern = patterns->zero_format;
  1241. }
  1242. // c. Else if x > 0, then
  1243. else if (number > 0) {
  1244. // i. Let pattern be patterns.[[positivePattern]].
  1245. pattern = patterns->positive_format;
  1246. }
  1247. // d. Else,
  1248. else {
  1249. // i. Let pattern be patterns.[[negativePattern]].
  1250. pattern = patterns->negative_format;
  1251. }
  1252. break;
  1253. default:
  1254. VERIFY_NOT_REACHED();
  1255. }
  1256. found_pattern = patterns.release_value();
  1257. // Handling of steps 9b/9g: Depending on the currency display and the format pattern found above,
  1258. // we might need to mutate the format pattern to inject a space between the currency display and
  1259. // the currency number.
  1260. if (number_format.style() == NumberFormat::Style::Currency) {
  1261. auto modified_pattern = Unicode::augment_currency_format_pattern(number_format.resolve_currency_display(), pattern);
  1262. if (modified_pattern.has_value())
  1263. return modified_pattern.release_value();
  1264. }
  1265. // 16. Return pattern.
  1266. return pattern;
  1267. }
  1268. // 15.1.15 GetNotationSubPattern ( numberFormat, exponent ), https://tc39.es/ecma402/#sec-getnotationsubpattern
  1269. Optional<StringView> get_notation_sub_pattern(NumberFormat& number_format, int exponent)
  1270. {
  1271. // 1. Let localeData be %NumberFormat%.[[LocaleData]].
  1272. // 2. Let dataLocale be numberFormat.[[DataLocale]].
  1273. // 3. Let dataLocaleData be localeData.[[<dataLocale>]].
  1274. // 4. Let notationSubPatterns be dataLocaleData.[[notationSubPatterns]].
  1275. // 5. Assert: notationSubPatterns is a Record (see 15.3.3).
  1276. // 6. Let notation be numberFormat.[[Notation]].
  1277. auto notation = number_format.notation();
  1278. // 7. If notation is "scientific" or notation is "engineering", then
  1279. if ((notation == NumberFormat::Notation::Scientific) || (notation == NumberFormat::Notation::Engineering)) {
  1280. // a. Return notationSubPatterns.[[scientific]].
  1281. auto notation_sub_patterns = Unicode::get_standard_number_system_format(number_format.data_locale(), number_format.numbering_system(), Unicode::StandardNumberFormatType::Scientific);
  1282. if (!notation_sub_patterns.has_value())
  1283. return {};
  1284. return notation_sub_patterns->zero_format;
  1285. }
  1286. // 8. Else if exponent is not 0, then
  1287. else if (exponent != 0) {
  1288. // a. Assert: notation is "compact".
  1289. VERIFY(notation == NumberFormat::Notation::Compact);
  1290. // b. Let compactDisplay be numberFormat.[[CompactDisplay]].
  1291. // c. Let compactPatterns be notationSubPatterns.[[compact]].[[<compactDisplay>]].
  1292. // d. Return compactPatterns.[[<exponent>]].
  1293. if (number_format.has_compact_format())
  1294. return number_format.compact_format().zero_format;
  1295. }
  1296. // 9. Else,
  1297. // a. Return "{number}".
  1298. return "{number}"sv;
  1299. }
  1300. // 15.1.16 ComputeExponent ( numberFormat, x ), https://tc39.es/ecma402/#sec-computeexponent
  1301. int compute_exponent(NumberFormat& number_format, double number)
  1302. {
  1303. // 1. If x = 0, then
  1304. if (number == 0.0) {
  1305. // a. Return 0.
  1306. return 0;
  1307. }
  1308. // 2. If x < 0, then
  1309. if (number < 0) {
  1310. // a. Let x = -x.
  1311. number *= -1;
  1312. }
  1313. // 3. Let magnitude be the base 10 logarithm of x rounded down to the nearest integer.
  1314. int magnitude = log10floor(number);
  1315. // 4. Let exponent be ComputeExponentForMagnitude(numberFormat, magnitude).
  1316. int exponent = compute_exponent_for_magniude(number_format, magnitude);
  1317. // 5. Let x be x × 10^(-exponent).
  1318. number *= pow(10, -exponent);
  1319. // 6. Let formatNumberResult be FormatNumericToString(numberFormat, x).
  1320. auto format_number_result = format_numeric_to_string(number_format, number);
  1321. // 7. If formatNumberResult.[[RoundedNumber]] = 0, then
  1322. if (format_number_result.rounded_number == 0) {
  1323. // a. Return exponent.
  1324. return exponent;
  1325. }
  1326. // 8. Let newMagnitude be the base 10 logarithm of formatNumberResult.[[RoundedNumber]] rounded down to the nearest integer.
  1327. int new_magnitude = log10floor(format_number_result.rounded_number);
  1328. // 9. If newMagnitude is magnitude – exponent, then
  1329. if (new_magnitude == magnitude - exponent) {
  1330. // a. Return exponent.
  1331. return exponent;
  1332. }
  1333. // 10. Return ComputeExponentForMagnitude(numberFormat, magnitude + 1).
  1334. return compute_exponent_for_magniude(number_format, magnitude + 1);
  1335. }
  1336. // 15.1.17 ComputeExponentForMagnitude ( numberFormat, magnitude ), https://tc39.es/ecma402/#sec-computeexponentformagnitude
  1337. int compute_exponent_for_magniude(NumberFormat& number_format, int magnitude)
  1338. {
  1339. // 1. Let notation be numberFormat.[[Notation]].
  1340. switch (number_format.notation()) {
  1341. // 2. If notation is "standard", then
  1342. case NumberFormat::Notation::Standard:
  1343. // a. Return 0.
  1344. return 0;
  1345. // 3. Else if notation is "scientific", then
  1346. case NumberFormat::Notation::Scientific:
  1347. // a. Return magnitude.
  1348. return magnitude;
  1349. // 4. Else if notation is "engineering", then
  1350. case NumberFormat::Notation::Engineering: {
  1351. // a. Let thousands be the greatest integer that is not greater than magnitude / 3.
  1352. double thousands = floor(static_cast<double>(magnitude) / 3.0);
  1353. // b. Return thousands × 3.
  1354. return static_cast<int>(thousands) * 3;
  1355. }
  1356. // 5. Else,
  1357. case NumberFormat::Notation::Compact: {
  1358. // a. Assert: notation is "compact".
  1359. VERIFY(number_format.has_compact_display());
  1360. // b. Let exponent be an implementation- and locale-dependent (ILD) integer by which to scale a number of the given magnitude in compact notation for the current locale.
  1361. // c. Return exponent.
  1362. Vector<Unicode::NumberFormat> format_rules;
  1363. if (number_format.style() == NumberFormat::Style::Currency)
  1364. format_rules = Unicode::get_compact_number_system_formats(number_format.data_locale(), number_format.numbering_system(), Unicode::CompactNumberFormatType::CurrencyShort);
  1365. else if (number_format.compact_display() == NumberFormat::CompactDisplay::Long)
  1366. format_rules = Unicode::get_compact_number_system_formats(number_format.data_locale(), number_format.numbering_system(), Unicode::CompactNumberFormatType::DecimalLong);
  1367. else
  1368. format_rules = Unicode::get_compact_number_system_formats(number_format.data_locale(), number_format.numbering_system(), Unicode::CompactNumberFormatType::DecimalShort);
  1369. Unicode::NumberFormat const* best_number_format = nullptr;
  1370. for (auto const& format_rule : format_rules) {
  1371. if (format_rule.magnitude > magnitude)
  1372. break;
  1373. best_number_format = &format_rule;
  1374. }
  1375. if (best_number_format == nullptr)
  1376. return 0;
  1377. number_format.set_compact_format(*best_number_format);
  1378. return best_number_format->exponent;
  1379. }
  1380. default:
  1381. VERIFY_NOT_REACHED();
  1382. }
  1383. }
  1384. }