NumberFormat.cpp 75 KB

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