NumberFormat.cpp 84 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972
  1. /*
  2. * Copyright (c) 2021-2023, Tim Flynn <trflynn89@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Checked.h>
  7. #include <AK/Utf8View.h>
  8. #include <LibCrypto/BigInt/SignedBigInteger.h>
  9. #include <LibJS/Runtime/AbstractOperations.h>
  10. #include <LibJS/Runtime/Array.h>
  11. #include <LibJS/Runtime/BigInt.h>
  12. #include <LibJS/Runtime/GlobalObject.h>
  13. #include <LibJS/Runtime/Intl/NumberFormat.h>
  14. #include <LibJS/Runtime/Intl/NumberFormatFunction.h>
  15. #include <LibJS/Runtime/Intl/PluralRules.h>
  16. #include <LibJS/Runtime/ThrowableStringBuilder.h>
  17. #include <LibUnicode/CurrencyCode.h>
  18. #include <math.h>
  19. #include <stdlib.h>
  20. namespace JS::Intl {
  21. NumberFormatBase::NumberFormatBase(Object& prototype)
  22. : Object(ConstructWithPrototypeTag::Tag, prototype)
  23. {
  24. }
  25. // 15 NumberFormat Objects, https://tc39.es/ecma402/#numberformat-objects
  26. NumberFormat::NumberFormat(Object& prototype)
  27. : NumberFormatBase(prototype)
  28. {
  29. }
  30. void NumberFormat::visit_edges(Cell::Visitor& visitor)
  31. {
  32. Base::visit_edges(visitor);
  33. if (m_bound_format)
  34. visitor.visit(m_bound_format);
  35. }
  36. void NumberFormat::set_style(StringView style)
  37. {
  38. if (style == "decimal"sv)
  39. m_style = Style::Decimal;
  40. else if (style == "percent"sv)
  41. m_style = Style::Percent;
  42. else if (style == "currency"sv)
  43. m_style = Style::Currency;
  44. else if (style == "unit"sv)
  45. m_style = Style::Unit;
  46. else
  47. VERIFY_NOT_REACHED();
  48. }
  49. StringView NumberFormat::style_string() const
  50. {
  51. switch (m_style) {
  52. case Style::Decimal:
  53. return "decimal"sv;
  54. case Style::Percent:
  55. return "percent"sv;
  56. case Style::Currency:
  57. return "currency"sv;
  58. case Style::Unit:
  59. return "unit"sv;
  60. default:
  61. VERIFY_NOT_REACHED();
  62. }
  63. }
  64. void NumberFormat::set_currency_display(StringView currency_display)
  65. {
  66. m_resolved_currency_display.clear();
  67. if (currency_display == "code"sv)
  68. m_currency_display = CurrencyDisplay::Code;
  69. else if (currency_display == "symbol"sv)
  70. m_currency_display = CurrencyDisplay::Symbol;
  71. else if (currency_display == "narrowSymbol"sv)
  72. m_currency_display = CurrencyDisplay::NarrowSymbol;
  73. else if (currency_display == "name"sv)
  74. m_currency_display = CurrencyDisplay::Name;
  75. else
  76. VERIFY_NOT_REACHED();
  77. }
  78. StringView NumberFormat::resolve_currency_display()
  79. {
  80. if (m_resolved_currency_display.has_value())
  81. return *m_resolved_currency_display;
  82. switch (currency_display()) {
  83. case NumberFormat::CurrencyDisplay::Code:
  84. m_resolved_currency_display = currency();
  85. break;
  86. case NumberFormat::CurrencyDisplay::Symbol:
  87. m_resolved_currency_display = ::Locale::get_locale_short_currency_mapping(data_locale(), currency());
  88. break;
  89. case NumberFormat::CurrencyDisplay::NarrowSymbol:
  90. m_resolved_currency_display = ::Locale::get_locale_narrow_currency_mapping(data_locale(), currency());
  91. break;
  92. case NumberFormat::CurrencyDisplay::Name:
  93. m_resolved_currency_display = ::Locale::get_locale_numeric_currency_mapping(data_locale(), currency());
  94. break;
  95. default:
  96. VERIFY_NOT_REACHED();
  97. }
  98. if (!m_resolved_currency_display.has_value())
  99. m_resolved_currency_display = currency();
  100. return *m_resolved_currency_display;
  101. }
  102. StringView NumberFormat::currency_display_string() const
  103. {
  104. VERIFY(m_currency_display.has_value());
  105. switch (*m_currency_display) {
  106. case CurrencyDisplay::Code:
  107. return "code"sv;
  108. case CurrencyDisplay::Symbol:
  109. return "symbol"sv;
  110. case CurrencyDisplay::NarrowSymbol:
  111. return "narrowSymbol"sv;
  112. case CurrencyDisplay::Name:
  113. return "name"sv;
  114. default:
  115. VERIFY_NOT_REACHED();
  116. }
  117. }
  118. void NumberFormat::set_currency_sign(StringView currency_sign)
  119. {
  120. if (currency_sign == "standard"sv)
  121. m_currency_sign = CurrencySign::Standard;
  122. else if (currency_sign == "accounting"sv)
  123. m_currency_sign = CurrencySign::Accounting;
  124. else
  125. VERIFY_NOT_REACHED();
  126. }
  127. StringView NumberFormat::currency_sign_string() const
  128. {
  129. VERIFY(m_currency_sign.has_value());
  130. switch (*m_currency_sign) {
  131. case CurrencySign::Standard:
  132. return "standard"sv;
  133. case CurrencySign::Accounting:
  134. return "accounting"sv;
  135. default:
  136. VERIFY_NOT_REACHED();
  137. }
  138. }
  139. StringView NumberFormatBase::rounding_type_string() const
  140. {
  141. switch (m_rounding_type) {
  142. case RoundingType::SignificantDigits:
  143. return "significantDigits"sv;
  144. case RoundingType::FractionDigits:
  145. return "fractionDigits"sv;
  146. case RoundingType::MorePrecision:
  147. return "morePrecision"sv;
  148. case RoundingType::LessPrecision:
  149. return "lessPrecision"sv;
  150. default:
  151. VERIFY_NOT_REACHED();
  152. }
  153. }
  154. StringView NumberFormatBase::computed_rounding_priority_string() const
  155. {
  156. switch (m_computed_rounding_priority) {
  157. case ComputedRoundingPriority::Auto:
  158. return "auto"sv;
  159. case ComputedRoundingPriority::MorePrecision:
  160. return "morePrecision"sv;
  161. case ComputedRoundingPriority::LessPrecision:
  162. return "lessPrecision"sv;
  163. default:
  164. VERIFY_NOT_REACHED();
  165. }
  166. }
  167. StringView NumberFormatBase::rounding_mode_string() const
  168. {
  169. switch (m_rounding_mode) {
  170. case RoundingMode::Ceil:
  171. return "ceil"sv;
  172. case RoundingMode::Expand:
  173. return "expand"sv;
  174. case RoundingMode::Floor:
  175. return "floor"sv;
  176. case RoundingMode::HalfCeil:
  177. return "halfCeil"sv;
  178. case RoundingMode::HalfEven:
  179. return "halfEven"sv;
  180. case RoundingMode::HalfExpand:
  181. return "halfExpand"sv;
  182. case RoundingMode::HalfFloor:
  183. return "halfFloor"sv;
  184. case RoundingMode::HalfTrunc:
  185. return "halfTrunc"sv;
  186. case RoundingMode::Trunc:
  187. return "trunc"sv;
  188. default:
  189. VERIFY_NOT_REACHED();
  190. }
  191. }
  192. void NumberFormatBase::set_rounding_mode(StringView rounding_mode)
  193. {
  194. if (rounding_mode == "ceil"sv)
  195. m_rounding_mode = RoundingMode::Ceil;
  196. else if (rounding_mode == "expand"sv)
  197. m_rounding_mode = RoundingMode::Expand;
  198. else if (rounding_mode == "floor"sv)
  199. m_rounding_mode = RoundingMode::Floor;
  200. else if (rounding_mode == "halfCeil"sv)
  201. m_rounding_mode = RoundingMode::HalfCeil;
  202. else if (rounding_mode == "halfEven"sv)
  203. m_rounding_mode = RoundingMode::HalfEven;
  204. else if (rounding_mode == "halfExpand"sv)
  205. m_rounding_mode = RoundingMode::HalfExpand;
  206. else if (rounding_mode == "halfFloor"sv)
  207. m_rounding_mode = RoundingMode::HalfFloor;
  208. else if (rounding_mode == "halfTrunc"sv)
  209. m_rounding_mode = RoundingMode::HalfTrunc;
  210. else if (rounding_mode == "trunc"sv)
  211. m_rounding_mode = RoundingMode::Trunc;
  212. else
  213. VERIFY_NOT_REACHED();
  214. }
  215. StringView NumberFormatBase::trailing_zero_display_string() const
  216. {
  217. switch (m_trailing_zero_display) {
  218. case TrailingZeroDisplay::Auto:
  219. return "auto"sv;
  220. case TrailingZeroDisplay::StripIfInteger:
  221. return "stripIfInteger"sv;
  222. default:
  223. VERIFY_NOT_REACHED();
  224. }
  225. }
  226. void NumberFormatBase::set_trailing_zero_display(StringView trailing_zero_display)
  227. {
  228. if (trailing_zero_display == "auto"sv)
  229. m_trailing_zero_display = TrailingZeroDisplay::Auto;
  230. else if (trailing_zero_display == "stripIfInteger"sv)
  231. m_trailing_zero_display = TrailingZeroDisplay::StripIfInteger;
  232. else
  233. VERIFY_NOT_REACHED();
  234. }
  235. ThrowCompletionOr<Value> NumberFormat::use_grouping_to_value(VM& vm) const
  236. {
  237. switch (m_use_grouping) {
  238. case UseGrouping::Always:
  239. return PrimitiveString::create(vm, "always"_string);
  240. case UseGrouping::Auto:
  241. return PrimitiveString::create(vm, "auto"_string);
  242. case UseGrouping::Min2:
  243. return PrimitiveString::create(vm, "min2"_string);
  244. case UseGrouping::False:
  245. return Value(false);
  246. default:
  247. VERIFY_NOT_REACHED();
  248. }
  249. }
  250. void NumberFormat::set_use_grouping(StringOrBoolean const& use_grouping)
  251. {
  252. use_grouping.visit(
  253. [this](StringView grouping) {
  254. if (grouping == "always"sv)
  255. m_use_grouping = UseGrouping::Always;
  256. else if (grouping == "auto"sv)
  257. m_use_grouping = UseGrouping::Auto;
  258. else if (grouping == "min2"sv)
  259. m_use_grouping = UseGrouping::Min2;
  260. else
  261. VERIFY_NOT_REACHED();
  262. },
  263. [this](bool grouping) {
  264. VERIFY(!grouping);
  265. m_use_grouping = UseGrouping::False;
  266. });
  267. }
  268. void NumberFormat::set_notation(StringView notation)
  269. {
  270. if (notation == "standard"sv)
  271. m_notation = Notation::Standard;
  272. else if (notation == "scientific"sv)
  273. m_notation = Notation::Scientific;
  274. else if (notation == "engineering"sv)
  275. m_notation = Notation::Engineering;
  276. else if (notation == "compact"sv)
  277. m_notation = Notation::Compact;
  278. else
  279. VERIFY_NOT_REACHED();
  280. }
  281. StringView NumberFormat::notation_string() const
  282. {
  283. switch (m_notation) {
  284. case Notation::Standard:
  285. return "standard"sv;
  286. case Notation::Scientific:
  287. return "scientific"sv;
  288. case Notation::Engineering:
  289. return "engineering"sv;
  290. case Notation::Compact:
  291. return "compact"sv;
  292. default:
  293. VERIFY_NOT_REACHED();
  294. }
  295. }
  296. void NumberFormat::set_compact_display(StringView compact_display)
  297. {
  298. if (compact_display == "short"sv)
  299. m_compact_display = CompactDisplay::Short;
  300. else if (compact_display == "long"sv)
  301. m_compact_display = CompactDisplay::Long;
  302. else
  303. VERIFY_NOT_REACHED();
  304. }
  305. StringView NumberFormat::compact_display_string() const
  306. {
  307. VERIFY(m_compact_display.has_value());
  308. switch (*m_compact_display) {
  309. case CompactDisplay::Short:
  310. return "short"sv;
  311. case CompactDisplay::Long:
  312. return "long"sv;
  313. default:
  314. VERIFY_NOT_REACHED();
  315. }
  316. }
  317. void NumberFormat::set_sign_display(StringView sign_display)
  318. {
  319. if (sign_display == "auto"sv)
  320. m_sign_display = SignDisplay::Auto;
  321. else if (sign_display == "never"sv)
  322. m_sign_display = SignDisplay::Never;
  323. else if (sign_display == "always"sv)
  324. m_sign_display = SignDisplay::Always;
  325. else if (sign_display == "exceptZero"sv)
  326. m_sign_display = SignDisplay::ExceptZero;
  327. else if (sign_display == "negative"sv)
  328. m_sign_display = SignDisplay::Negative;
  329. else
  330. VERIFY_NOT_REACHED();
  331. }
  332. StringView NumberFormat::sign_display_string() const
  333. {
  334. switch (m_sign_display) {
  335. case SignDisplay::Auto:
  336. return "auto"sv;
  337. case SignDisplay::Never:
  338. return "never"sv;
  339. case SignDisplay::Always:
  340. return "always"sv;
  341. case SignDisplay::ExceptZero:
  342. return "exceptZero"sv;
  343. case SignDisplay::Negative:
  344. return "negative"sv;
  345. default:
  346. VERIFY_NOT_REACHED();
  347. }
  348. }
  349. // 15.5.1 CurrencyDigits ( currency ), https://tc39.es/ecma402/#sec-currencydigits
  350. int currency_digits(StringView currency)
  351. {
  352. // 1. If the ISO 4217 currency and funds code list contains currency as an alphabetic code, return the minor
  353. // unit value corresponding to the currency from the list; otherwise, return 2.
  354. if (auto currency_code = Unicode::get_currency_code(currency); currency_code.has_value())
  355. return currency_code->minor_unit.value_or(2);
  356. return 2;
  357. }
  358. // 15.5.3 FormatNumericToString ( intlObject, x ), https://tc39.es/ecma402/#sec-formatnumberstring
  359. ThrowCompletionOr<FormatResult> format_numeric_to_string(VM& vm, NumberFormatBase const& intl_object, MathematicalValue number)
  360. {
  361. bool is_negative = false;
  362. // 1. If x is negative-zero, then
  363. if (number.is_negative_zero()) {
  364. // a. Let isNegative be true.
  365. is_negative = true;
  366. // b. Set x to 0.
  367. number = MathematicalValue(0.0);
  368. }
  369. // 2. Else,
  370. else {
  371. // a. Assert: x is a mathematical value.
  372. VERIFY(number.is_mathematical_value());
  373. // b. If x < 0, let isNegative be true; else let isNegative be false.
  374. is_negative = number.is_negative();
  375. // c. If isNegative is true, then
  376. if (is_negative) {
  377. // i. Set x to -x.
  378. number.negate();
  379. }
  380. }
  381. // 3. Let unsignedRoundingMode be GetUnsignedRoundingMode(intlObject.[[RoundingMode]], isNegative).
  382. auto unsigned_rounding_mode = get_unsigned_rounding_mode(intl_object.rounding_mode(), is_negative);
  383. RawFormatResult result {};
  384. switch (intl_object.rounding_type()) {
  385. // 4. If intlObject.[[RoundingType]] is significantDigits, then
  386. case NumberFormatBase::RoundingType::SignificantDigits:
  387. // a. Let result be ToRawPrecision(x, intlObject.[[MinimumSignificantDigits]], intlObject.[[MaximumSignificantDigits]], unsignedRoundingMode).
  388. result = MUST_OR_THROW_OOM(to_raw_precision(vm, number, intl_object.min_significant_digits(), intl_object.max_significant_digits(), unsigned_rounding_mode));
  389. break;
  390. // 5. Else if intlObject.[[RoundingType]] is fractionDigits, then
  391. case NumberFormatBase::RoundingType::FractionDigits:
  392. // a. Let result be ToRawFixed(x, intlObject.[[MinimumFractionDigits]], intlObject.[[MaximumFractionDigits]], intlObject.[[RoundingIncrement]], unsignedRoundingMode).
  393. result = MUST_OR_THROW_OOM(to_raw_fixed(vm, number, intl_object.min_fraction_digits(), intl_object.max_fraction_digits(), intl_object.rounding_increment(), unsigned_rounding_mode));
  394. break;
  395. // 6. Else,
  396. case NumberFormatBase::RoundingType::MorePrecision:
  397. case NumberFormatBase::RoundingType::LessPrecision: {
  398. // a. Let sResult be ToRawPrecision(x, intlObject.[[MinimumSignificantDigits]], intlObject.[[MaximumSignificantDigits]], unsignedRoundingMode).
  399. auto significant_result = MUST_OR_THROW_OOM(to_raw_precision(vm, number, intl_object.min_significant_digits(), intl_object.max_significant_digits(), unsigned_rounding_mode));
  400. // b. Let fResult be ToRawFixed(x, intlObject.[[MinimumFractionDigits]], intlObject.[[MaximumFractionDigits]], intlObject.[[RoundingIncrement]], unsignedRoundingMode).
  401. auto fraction_result = MUST_OR_THROW_OOM(to_raw_fixed(vm, number, intl_object.min_fraction_digits(), intl_object.max_fraction_digits(), intl_object.rounding_increment(), unsigned_rounding_mode));
  402. // c. If intlObj.[[RoundingType]] is morePrecision, then
  403. if (intl_object.rounding_type() == NumberFormatBase::RoundingType::MorePrecision) {
  404. // i. If sResult.[[RoundingMagnitude]] ≤ fResult.[[RoundingMagnitude]], then
  405. if (significant_result.rounding_magnitude <= fraction_result.rounding_magnitude) {
  406. // 1. Let result be sResult.
  407. result = move(significant_result);
  408. }
  409. // ii. Else,
  410. else {
  411. // 2. Let result be fResult.
  412. result = move(fraction_result);
  413. }
  414. }
  415. // d. Else,
  416. else {
  417. // i. Assert: intlObj.[[RoundingType]] is lessPrecision.
  418. VERIFY(intl_object.rounding_type() == NumberFormatBase::RoundingType::LessPrecision);
  419. // ii. If sResult.[[RoundingMagnitude]] ≤ fResult.[[RoundingMagnitude]], then
  420. if (significant_result.rounding_magnitude <= fraction_result.rounding_magnitude) {
  421. // 1. Let result be fResult.
  422. result = move(fraction_result);
  423. }
  424. // iii. Else,
  425. else {
  426. // 1. Let result be sResult.
  427. result = move(significant_result);
  428. }
  429. }
  430. break;
  431. }
  432. default:
  433. VERIFY_NOT_REACHED();
  434. }
  435. // 7. Set x to result.[[RoundedNumber]].
  436. number = move(result.rounded_number);
  437. // 8. Let string be result.[[FormattedString]].
  438. auto string = move(result.formatted_string);
  439. // 9. If intlObject.[[TrailingZeroDisplay]] is "stripIfInteger" and x modulo 1 = 0, then
  440. if ((intl_object.trailing_zero_display() == NumberFormat::TrailingZeroDisplay::StripIfInteger) && number.modulo_is_zero(1)) {
  441. // a. Let i be StringIndexOf(string, ".", 0).
  442. auto index = string.find_byte_offset('.');
  443. // b. If i ≠ -1, set string to the substring of string from 0 to i.
  444. if (index.has_value())
  445. string = TRY_OR_THROW_OOM(vm, string.substring_from_byte_offset(0, *index));
  446. }
  447. // 10. Let int be result.[[IntegerDigitsCount]].
  448. int digits = result.digits;
  449. // 11. Let minInteger be intlObject.[[MinimumIntegerDigits]].
  450. int min_integer = intl_object.min_integer_digits();
  451. // 12. If int < minInteger, then
  452. if (digits < min_integer) {
  453. // a. Let forwardZeros be the String consisting of minInteger - int occurrences of the code unit 0x0030 (DIGIT ZERO).
  454. auto forward_zeros = TRY_OR_THROW_OOM(vm, String::repeated('0', min_integer - digits));
  455. // b. Set string to the string-concatenation of forwardZeros and string.
  456. string = TRY_OR_THROW_OOM(vm, String::formatted("{}{}", forward_zeros, string));
  457. }
  458. // 13. If isNegative is true, then
  459. if (is_negative) {
  460. // a. If x is 0, set x to negative-zero. Otherwise, set x to -x.
  461. if (number.is_zero())
  462. number = MathematicalValue { MathematicalValue::Symbol::NegativeZero };
  463. else
  464. number.negate();
  465. }
  466. // 14. Return the Record { [[RoundedNumber]]: x, [[FormattedString]]: string }.
  467. return FormatResult { move(string), move(number) };
  468. }
  469. // 15.5.4 PartitionNumberPattern ( numberFormat, x ), https://tc39.es/ecma402/#sec-partitionnumberpattern
  470. ThrowCompletionOr<Vector<PatternPartition>> partition_number_pattern(VM& vm, NumberFormat& number_format, MathematicalValue number)
  471. {
  472. // 1. Let exponent be 0.
  473. int exponent = 0;
  474. String formatted_string;
  475. // 2. If x is not-a-number, then
  476. if (number.is_nan()) {
  477. // a. Let n be an implementation- and locale-dependent (ILD) String value indicating the NaN value.
  478. auto symbol = ::Locale::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), ::Locale::NumericSymbol::NaN).value_or("NaN"sv);
  479. formatted_string = TRY_OR_THROW_OOM(vm, String::from_utf8(symbol));
  480. }
  481. // 3. Else if x is positive-infinity, then
  482. else if (number.is_positive_infinity()) {
  483. // a. Let n be an ILD String value indicating positive infinity.
  484. auto symbol = ::Locale::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), ::Locale::NumericSymbol::Infinity).value_or("infinity"sv);
  485. formatted_string = TRY_OR_THROW_OOM(vm, String::from_utf8(symbol));
  486. }
  487. // 4. Else if x is negative-infinity, then
  488. else if (number.is_negative_infinity()) {
  489. // a. Let n be an ILD String value indicating negative infinity.
  490. // NOTE: The CLDR does not contain unique strings for negative infinity. The negative sign will
  491. // be inserted by the pattern returned from GetNumberFormatPattern.
  492. auto symbol = ::Locale::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), ::Locale::NumericSymbol::Infinity).value_or("infinity"sv);
  493. formatted_string = TRY_OR_THROW_OOM(vm, String::from_utf8(symbol));
  494. }
  495. // 5. Else,
  496. else {
  497. // a. If x is not negative-zero,
  498. if (!number.is_negative_zero()) {
  499. // i. Assert: x is a mathematical value.
  500. VERIFY(number.is_mathematical_value());
  501. // ii. If numberFormat.[[Style]] is "percent", let x be 100 × x.
  502. if (number_format.style() == NumberFormat::Style::Percent)
  503. number = number.multiplied_by(100);
  504. // iii. Let exponent be ComputeExponent(numberFormat, x).
  505. exponent = MUST_OR_THROW_OOM(compute_exponent(vm, number_format, number));
  506. // iv. Let x be x × 10^-exponent.
  507. number = number.multiplied_by_power(-exponent);
  508. }
  509. // b. Let formatNumberResult be FormatNumericToString(numberFormat, x).
  510. auto format_number_result = MUST_OR_THROW_OOM(format_numeric_to_string(vm, number_format, move(number)));
  511. // c. Let n be formatNumberResult.[[FormattedString]].
  512. formatted_string = move(format_number_result.formatted_string);
  513. // d. Let x be formatNumberResult.[[RoundedNumber]].
  514. number = move(format_number_result.rounded_number);
  515. }
  516. ::Locale::NumberFormat found_pattern {};
  517. // 6. Let pattern be GetNumberFormatPattern(numberFormat, x).
  518. auto pattern = MUST_OR_THROW_OOM(get_number_format_pattern(vm, number_format, number, found_pattern));
  519. if (!pattern.has_value())
  520. return Vector<PatternPartition> {};
  521. // 7. Let result be a new empty List.
  522. Vector<PatternPartition> result;
  523. // 8. Let patternParts be PartitionPattern(pattern).
  524. auto pattern_parts = MUST_OR_THROW_OOM(pattern->visit([&](auto const& p) { return partition_pattern(vm, p); }));
  525. // 9. For each Record { [[Type]], [[Value]] } patternPart of patternParts, do
  526. for (auto& pattern_part : pattern_parts) {
  527. // a. Let p be patternPart.[[Type]].
  528. auto part = pattern_part.type;
  529. // b. If p is "literal", then
  530. if (part == "literal"sv) {
  531. // i. Append a new Record { [[Type]]: "literal", [[Value]]: patternPart.[[Value]] } as the last element of result.
  532. TRY_OR_THROW_OOM(vm, result.try_append({ "literal"sv, move(pattern_part.value) }));
  533. }
  534. // c. Else if p is equal to "number", then
  535. else if (part == "number"sv) {
  536. // i. Let notationSubParts be PartitionNotationSubPattern(numberFormat, x, n, exponent).
  537. auto notation_sub_parts = MUST_OR_THROW_OOM(partition_notation_sub_pattern(vm, number_format, number, formatted_string, exponent));
  538. // ii. Append all elements of notationSubParts to result.
  539. TRY_OR_THROW_OOM(vm, result.try_extend(move(notation_sub_parts)));
  540. }
  541. // d. Else if p is equal to "plusSign", then
  542. else if (part == "plusSign"sv) {
  543. // i. Let plusSignSymbol be the ILND String representing the plus sign.
  544. auto plus_sign_symbol = ::Locale::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), ::Locale::NumericSymbol::PlusSign).value_or("+"sv);
  545. // ii. Append a new Record { [[Type]]: "plusSign", [[Value]]: plusSignSymbol } as the last element of result.
  546. TRY_OR_THROW_OOM(vm, result.try_append({ "plusSign"sv, TRY_OR_THROW_OOM(vm, String::from_utf8(plus_sign_symbol)) }));
  547. }
  548. // e. Else if p is equal to "minusSign", then
  549. else if (part == "minusSign"sv) {
  550. // i. Let minusSignSymbol be the ILND String representing the minus sign.
  551. auto minus_sign_symbol = ::Locale::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), ::Locale::NumericSymbol::MinusSign).value_or("-"sv);
  552. // ii. Append a new Record { [[Type]]: "minusSign", [[Value]]: minusSignSymbol } as the last element of result.
  553. TRY_OR_THROW_OOM(vm, result.try_append({ "minusSign"sv, TRY_OR_THROW_OOM(vm, String::from_utf8(minus_sign_symbol)) }));
  554. }
  555. // f. Else if p is equal to "percentSign" and numberFormat.[[Style]] is "percent", then
  556. else if ((part == "percentSign"sv) && (number_format.style() == NumberFormat::Style::Percent)) {
  557. // i. Let percentSignSymbol be the ILND String representing the percent sign.
  558. auto percent_sign_symbol = ::Locale::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), ::Locale::NumericSymbol::PercentSign).value_or("%"sv);
  559. // ii. Append a new Record { [[Type]]: "percentSign", [[Value]]: percentSignSymbol } as the last element of result.
  560. TRY_OR_THROW_OOM(vm, result.try_append({ "percentSign"sv, TRY_OR_THROW_OOM(vm, String::from_utf8(percent_sign_symbol)) }));
  561. }
  562. // g. Else if p is equal to "unitPrefix" and numberFormat.[[Style]] is "unit", then
  563. // h. Else if p is equal to "unitSuffix" and numberFormat.[[Style]] is "unit", then
  564. else if ((part.starts_with("unitIdentifier:"sv)) && (number_format.style() == NumberFormat::Style::Unit)) {
  565. // Note: Our implementation combines "unitPrefix" and "unitSuffix" into one field, "unitIdentifier".
  566. auto identifier_index = part.substring_view("unitIdentifier:"sv.length()).to_uint();
  567. VERIFY(identifier_index.has_value());
  568. // i. Let unit be numberFormat.[[Unit]].
  569. // ii. Let unitDisplay be numberFormat.[[UnitDisplay]].
  570. // 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.
  571. auto unit_identifier = found_pattern.identifiers[*identifier_index];
  572. // iv. Append a new Record { [[Type]]: "unit", [[Value]]: mu } as the last element of result.
  573. TRY_OR_THROW_OOM(vm, result.try_append({ "unit"sv, TRY_OR_THROW_OOM(vm, String::from_utf8(unit_identifier)) }));
  574. }
  575. // i. Else if p is equal to "currencyCode" and numberFormat.[[Style]] is "currency", then
  576. // j. Else if p is equal to "currencyPrefix" and numberFormat.[[Style]] is "currency", then
  577. // k. Else if p is equal to "currencySuffix" and numberFormat.[[Style]] is "currency", then
  578. //
  579. // Note: Our implementation manipulates the format string to inject/remove spacing around the
  580. // currency code during GetNumberFormatPattern so that we do not have to do currency
  581. // display / plurality lookups more than once.
  582. else if ((part == "currency"sv) && (number_format.style() == NumberFormat::Style::Currency)) {
  583. auto currency = number_format.resolve_currency_display();
  584. TRY_OR_THROW_OOM(vm, result.try_append({ "currency"sv, TRY_OR_THROW_OOM(vm, String::from_utf8(currency)) }));
  585. }
  586. // l. Else,
  587. else {
  588. // i. Let unknown be an ILND String based on x and p.
  589. // ii. Append a new Record { [[Type]]: "unknown", [[Value]]: unknown } as the last element of result.
  590. // LibUnicode doesn't generate any "unknown" patterns.
  591. VERIFY_NOT_REACHED();
  592. }
  593. }
  594. // 10. Return result.
  595. return result;
  596. }
  597. static ThrowCompletionOr<Vector<String>> separate_integer_into_groups(VM& vm, ::Locale::NumberGroupings const& grouping_sizes, String integer, NumberFormat::UseGrouping use_grouping)
  598. {
  599. auto default_group = [&]() -> ThrowCompletionOr<Vector<String>> {
  600. Vector<String> groups;
  601. TRY_OR_THROW_OOM(vm, groups.try_append(move(integer)));
  602. return groups;
  603. };
  604. auto utf8_integer = integer.code_points();
  605. if (utf8_integer.length() <= grouping_sizes.primary_grouping_size)
  606. return default_group();
  607. size_t index = utf8_integer.length() - grouping_sizes.primary_grouping_size;
  608. switch (use_grouping) {
  609. case NumberFormat::UseGrouping::Min2:
  610. if (utf8_integer.length() < 5)
  611. return default_group();
  612. break;
  613. case NumberFormat::UseGrouping::Auto:
  614. if (index < grouping_sizes.minimum_grouping_digits)
  615. return default_group();
  616. break;
  617. case NumberFormat::UseGrouping::Always:
  618. break;
  619. default:
  620. VERIFY_NOT_REACHED();
  621. }
  622. Vector<String> groups;
  623. auto add_group = [&](size_t index, size_t length) -> ThrowCompletionOr<void> {
  624. length = utf8_integer.unicode_substring_view(index, length).byte_length();
  625. index = utf8_integer.byte_offset_of(index);
  626. auto group = TRY_OR_THROW_OOM(vm, integer.substring_from_byte_offset_with_shared_superstring(index, length));
  627. TRY_OR_THROW_OOM(vm, groups.try_prepend(move(group)));
  628. return {};
  629. };
  630. MUST_OR_THROW_OOM(add_group(index, grouping_sizes.primary_grouping_size));
  631. while (index > grouping_sizes.secondary_grouping_size) {
  632. index -= grouping_sizes.secondary_grouping_size;
  633. MUST_OR_THROW_OOM(add_group(index, grouping_sizes.secondary_grouping_size));
  634. }
  635. if (index > 0)
  636. MUST_OR_THROW_OOM(add_group(0, index));
  637. return groups;
  638. }
  639. // 15.5.5 PartitionNotationSubPattern ( numberFormat, x, n, exponent ), https://tc39.es/ecma402/#sec-partitionnotationsubpattern
  640. ThrowCompletionOr<Vector<PatternPartition>> partition_notation_sub_pattern(VM& vm, NumberFormat& number_format, MathematicalValue const& number, String formatted_string, int exponent)
  641. {
  642. // 1. Let result be a new empty List.
  643. Vector<PatternPartition> result;
  644. auto grouping_sizes = ::Locale::get_number_system_groupings(number_format.data_locale(), number_format.numbering_system());
  645. if (!grouping_sizes.has_value())
  646. return Vector<PatternPartition> {};
  647. // 2. If x is not-a-number, then
  648. if (number.is_nan()) {
  649. // a. Append a new Record { [[Type]]: "nan", [[Value]]: n } as the last element of result.
  650. TRY_OR_THROW_OOM(vm, result.try_append({ "nan"sv, move(formatted_string) }));
  651. }
  652. // 3. Else if x is positive-infinity or negative-infinity, then
  653. else if (number.is_positive_infinity() || number.is_negative_infinity()) {
  654. // a. Append a new Record { [[Type]]: "infinity", [[Value]]: n } as the last element of result.
  655. TRY_OR_THROW_OOM(vm, result.try_append({ "infinity"sv, move(formatted_string) }));
  656. }
  657. // 4. Else,
  658. else {
  659. // a. Let notationSubPattern be GetNotationSubPattern(numberFormat, exponent).
  660. auto notation_sub_pattern = MUST_OR_THROW_OOM(get_notation_sub_pattern(vm, number_format, exponent));
  661. if (!notation_sub_pattern.has_value())
  662. return Vector<PatternPartition> {};
  663. // b. Let patternParts be PartitionPattern(notationSubPattern).
  664. auto pattern_parts = MUST_OR_THROW_OOM(partition_pattern(vm, *notation_sub_pattern));
  665. // c. For each Record { [[Type]], [[Value]] } patternPart of patternParts, do
  666. for (auto& pattern_part : pattern_parts) {
  667. // i. Let p be patternPart.[[Type]].
  668. auto part = pattern_part.type;
  669. // ii. If p is "literal", then
  670. if (part == "literal"sv) {
  671. // 1. Append a new Record { [[Type]]: "literal", [[Value]]: patternPart.[[Value]] } as the last element of result.
  672. TRY_OR_THROW_OOM(vm, result.try_append({ "literal"sv, move(pattern_part.value) }));
  673. }
  674. // iii. Else if p is equal to "number", then
  675. else if (part == "number"sv) {
  676. // 1. If the numberFormat.[[NumberingSystem]] matches one of the values in the "Numbering System" column of Table 14 below, then
  677. // a. Let digits be a List whose elements are the code points specified in the "Digits" column of the matching row in Table 14.
  678. // b. Assert: The length of digits is 10.
  679. // c. Let transliterated be the empty String.
  680. // d. Let len be the length of n.
  681. // e. Let position be 0.
  682. // f. Repeat, while position < len,
  683. // i. Let c be the code unit at index position within n.
  684. // ii. If 0x0030 ≤ c ≤ 0x0039, then
  685. // i. NOTE: c is an ASCII digit.
  686. // ii. Let i be c - 0x0030.
  687. // iii. Set c to CodePointsToString(« digits[i] »).
  688. // iii. Set transliterated to the string-concatenation of transliterated and c.
  689. // iv. Set position to position + 1.
  690. // g. Set n to transliterated.
  691. // 2. Else use an implementation dependent algorithm to map n to the appropriate representation of n in the given numbering system.
  692. formatted_string = TRY_OR_THROW_OOM(vm, ::Locale::replace_digits_for_number_system(number_format.numbering_system(), formatted_string));
  693. // 3. Let decimalSepIndex be StringIndexOf(n, ".", 0).
  694. auto decimal_sep_index = formatted_string.find_byte_offset('.');
  695. String integer;
  696. Optional<String> fraction;
  697. // 4. If decimalSepIndex > 0, then
  698. if (decimal_sep_index.has_value() && (*decimal_sep_index > 0)) {
  699. // a. Let integer be the substring of n from position 0, inclusive, to position decimalSepIndex, exclusive.
  700. integer = TRY_OR_THROW_OOM(vm, formatted_string.substring_from_byte_offset_with_shared_superstring(0, *decimal_sep_index));
  701. // b. Let fraction be the substring of n from position decimalSepIndex, exclusive, to the end of n.
  702. fraction = TRY_OR_THROW_OOM(vm, formatted_string.substring_from_byte_offset_with_shared_superstring(*decimal_sep_index + 1));
  703. }
  704. // 5. Else,
  705. else {
  706. // a. Let integer be n.
  707. integer = move(formatted_string);
  708. // b. Let fraction be undefined.
  709. }
  710. // 6. If the numberFormat.[[UseGrouping]] is false, then
  711. if (number_format.use_grouping() == NumberFormat::UseGrouping::False) {
  712. // a. Append a new Record { [[Type]]: "integer", [[Value]]: integer } as the last element of result.
  713. TRY_OR_THROW_OOM(vm, result.try_append({ "integer"sv, move(integer) }));
  714. }
  715. // 7. Else,
  716. else {
  717. // a. Let groupSepSymbol be the implementation-, locale-, and numbering system-dependent (ILND) String representing the grouping separator.
  718. auto group_sep_symbol = ::Locale::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), ::Locale::NumericSymbol::Group).value_or(","sv);
  719. // 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, which may depend on the value of numberFormat.[[UseGrouping]].
  720. auto groups = MUST_OR_THROW_OOM(separate_integer_into_groups(vm, *grouping_sizes, move(integer), number_format.use_grouping()));
  721. // c. Assert: The number of elements in groups List is greater than 0.
  722. VERIFY(!groups.is_empty());
  723. // d. Repeat, while groups List is not empty,
  724. while (!groups.is_empty()) {
  725. // i. Remove the first element from groups and let integerGroup be the value of that element.
  726. auto integer_group = groups.take_first();
  727. // ii. Append a new Record { [[Type]]: "integer", [[Value]]: integerGroup } as the last element of result.
  728. TRY_OR_THROW_OOM(vm, result.try_append({ "integer"sv, move(integer_group) }));
  729. // iii. If groups List is not empty, then
  730. if (!groups.is_empty()) {
  731. // i. Append a new Record { [[Type]]: "group", [[Value]]: groupSepSymbol } as the last element of result.
  732. TRY_OR_THROW_OOM(vm, result.try_append({ "group"sv, TRY_OR_THROW_OOM(vm, String::from_utf8(group_sep_symbol)) }));
  733. }
  734. }
  735. }
  736. // 8. If fraction is not undefined, then
  737. if (fraction.has_value()) {
  738. // a. Let decimalSepSymbol be the ILND String representing the decimal separator.
  739. auto decimal_sep_symbol = ::Locale::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), ::Locale::NumericSymbol::Decimal).value_or("."sv);
  740. // b. Append a new Record { [[Type]]: "decimal", [[Value]]: decimalSepSymbol } as the last element of result.
  741. TRY_OR_THROW_OOM(vm, result.try_append({ "decimal"sv, TRY_OR_THROW_OOM(vm, String::from_utf8(decimal_sep_symbol)) }));
  742. // c. Append a new Record { [[Type]]: "fraction", [[Value]]: fraction } as the last element of result.
  743. TRY_OR_THROW_OOM(vm, result.try_append({ "fraction"sv, fraction.release_value() }));
  744. }
  745. }
  746. // iv. Else if p is equal to "compactSymbol", then
  747. // v. Else if p is equal to "compactName", then
  748. else if (part.starts_with("compactIdentifier:"sv)) {
  749. // Note: Our implementation combines "compactSymbol" and "compactName" into one field, "compactIdentifier".
  750. auto identifier_index = part.substring_view("compactIdentifier:"sv.length()).to_uint();
  751. VERIFY(identifier_index.has_value());
  752. // 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.
  753. auto compact_identifier = number_format.compact_format().identifiers[*identifier_index];
  754. // 2. Append a new Record { [[Type]]: "compact", [[Value]]: compactSymbol } as the last element of result.
  755. TRY_OR_THROW_OOM(vm, result.try_append({ "compact"sv, TRY_OR_THROW_OOM(vm, String::from_utf8(compact_identifier)) }));
  756. }
  757. // vi. Else if p is equal to "scientificSeparator", then
  758. else if (part == "scientificSeparator"sv) {
  759. // 1. Let scientificSeparator be the ILND String representing the exponent separator.
  760. auto scientific_separator = ::Locale::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), ::Locale::NumericSymbol::Exponential).value_or("E"sv);
  761. // 2. Append a new Record { [[Type]]: "exponentSeparator", [[Value]]: scientificSeparator } as the last element of result.
  762. TRY_OR_THROW_OOM(vm, result.try_append({ "exponentSeparator"sv, TRY_OR_THROW_OOM(vm, String::from_utf8(scientific_separator)) }));
  763. }
  764. // vii. Else if p is equal to "scientificExponent", then
  765. else if (part == "scientificExponent"sv) {
  766. // 1. If exponent < 0, then
  767. if (exponent < 0) {
  768. // a. Let minusSignSymbol be the ILND String representing the minus sign.
  769. auto minus_sign_symbol = ::Locale::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), ::Locale::NumericSymbol::MinusSign).value_or("-"sv);
  770. // b. Append a new Record { [[Type]]: "exponentMinusSign", [[Value]]: minusSignSymbol } as the last element of result.
  771. TRY_OR_THROW_OOM(vm, result.try_append({ "exponentMinusSign"sv, TRY_OR_THROW_OOM(vm, String::from_utf8(minus_sign_symbol)) }));
  772. // c. Let exponent be -exponent.
  773. exponent *= -1;
  774. }
  775. // 2. Let exponentResult be ToRawFixed(exponent, 0, 0, 1, undefined).
  776. auto exponent_value = MathematicalValue { static_cast<double>(exponent) };
  777. auto exponent_result = MUST_OR_THROW_OOM(to_raw_fixed(vm, exponent_value, 0, 0, 1, {}));
  778. // FIXME: The spec does not say to do this, but all of major engines perform this replacement.
  779. // Without this, formatting with non-Latin numbering systems will produce non-localized results.
  780. exponent_result.formatted_string = TRY_OR_THROW_OOM(vm, ::Locale::replace_digits_for_number_system(number_format.numbering_system(), exponent_result.formatted_string));
  781. // 3. Append a new Record { [[Type]]: "exponentInteger", [[Value]]: exponentResult.[[FormattedString]] } as the last element of result.
  782. TRY_OR_THROW_OOM(vm, result.try_append({ "exponentInteger"sv, move(exponent_result.formatted_string) }));
  783. }
  784. // viii. Else,
  785. else {
  786. // 1. Let unknown be an ILND String based on x and p.
  787. // 2. Append a new Record { [[Type]]: "unknown", [[Value]]: unknown } as the last element of result.
  788. // LibUnicode doesn't generate any "unknown" patterns.
  789. VERIFY_NOT_REACHED();
  790. }
  791. }
  792. }
  793. // 5. Return result.
  794. return result;
  795. }
  796. // 15.5.6 FormatNumeric ( numberFormat, x ), https://tc39.es/ecma402/#sec-formatnumber
  797. ThrowCompletionOr<String> format_numeric(VM& vm, NumberFormat& number_format, MathematicalValue number)
  798. {
  799. // 1. Let parts be ? PartitionNumberPattern(numberFormat, x).
  800. auto parts = TRY(partition_number_pattern(vm, number_format, move(number)));
  801. // 2. Let result be the empty String.
  802. ThrowableStringBuilder result(vm);
  803. // 3. For each Record { [[Type]], [[Value]] } part in parts, do
  804. for (auto& part : parts) {
  805. // a. Set result to the string-concatenation of result and part.[[Value]].
  806. TRY(result.append(part.value));
  807. }
  808. // 4. Return result.
  809. return result.to_string();
  810. }
  811. // 15.5.7 FormatNumericToParts ( numberFormat, x ), https://tc39.es/ecma402/#sec-formatnumbertoparts
  812. ThrowCompletionOr<Array*> format_numeric_to_parts(VM& vm, NumberFormat& number_format, MathematicalValue number)
  813. {
  814. auto& realm = *vm.current_realm();
  815. // 1. Let parts be ? PartitionNumberPattern(numberFormat, x).
  816. auto parts = TRY(partition_number_pattern(vm, number_format, move(number)));
  817. // 2. Let result be ! ArrayCreate(0).
  818. auto result = MUST(Array::create(realm, 0));
  819. // 3. Let n be 0.
  820. size_t n = 0;
  821. // 4. For each Record { [[Type]], [[Value]] } part in parts, do
  822. for (auto& part : parts) {
  823. // a. Let O be OrdinaryObjectCreate(%Object.prototype%).
  824. auto object = Object::create(realm, realm.intrinsics().object_prototype());
  825. // b. Perform ! CreateDataPropertyOrThrow(O, "type", part.[[Type]]).
  826. MUST(object->create_data_property_or_throw(vm.names.type, PrimitiveString::create(vm, part.type)));
  827. // c. Perform ! CreateDataPropertyOrThrow(O, "value", part.[[Value]]).
  828. MUST(object->create_data_property_or_throw(vm.names.value, PrimitiveString::create(vm, move(part.value))));
  829. // d. Perform ! CreateDataPropertyOrThrow(result, ! ToString(n), O).
  830. MUST(result->create_data_property_or_throw(n, object));
  831. // e. Increment n by 1.
  832. ++n;
  833. }
  834. // 5. Return result.
  835. return result.ptr();
  836. }
  837. static ErrorOr<String> cut_trailing_zeroes(StringView string, int cut)
  838. {
  839. // These steps are exactly the same between ToRawPrecision and ToRawFixed.
  840. // Repeat, while cut > 0 and the last code unit of m is 0x0030 (DIGIT ZERO),
  841. while ((cut > 0) && string.ends_with('0')) {
  842. // Remove the last code unit from m.
  843. string = string.substring_view(0, string.length() - 1);
  844. // Decrease cut by 1.
  845. --cut;
  846. }
  847. // If the last code unit of m is 0x002E (FULL STOP), then
  848. if (string.ends_with('.')) {
  849. // Remove the last code unit from m.
  850. string = string.substring_view(0, string.length() - 1);
  851. }
  852. return String::from_utf8(string);
  853. }
  854. enum class PreferredResult {
  855. LessThanNumber,
  856. GreaterThanNumber,
  857. };
  858. struct RawPrecisionResult {
  859. MathematicalValue number;
  860. int exponent { 0 };
  861. MathematicalValue rounded;
  862. };
  863. // ToRawPrecisionFn, https://tc39.es/ecma402/#eqn-ToRawPrecisionFn
  864. static ThrowCompletionOr<RawPrecisionResult> to_raw_precision_function(VM& vm, MathematicalValue const& number, int precision, PreferredResult mode)
  865. {
  866. RawPrecisionResult result {};
  867. result.exponent = MUST_OR_THROW_OOM(number.logarithmic_floor(vm));
  868. if (number.is_number()) {
  869. result.number = number.divided_by_power(result.exponent - precision + 1);
  870. switch (mode) {
  871. case PreferredResult::LessThanNumber:
  872. result.number = MathematicalValue { floor(result.number.as_number()) };
  873. break;
  874. case PreferredResult::GreaterThanNumber:
  875. result.number = MathematicalValue { ceil(result.number.as_number()) };
  876. break;
  877. }
  878. } else {
  879. // NOTE: In order to round the BigInt to the proper precision, this computation is initially off by a
  880. // factor of 10. This lets us inspect the ones digit and then round up if needed.
  881. result.number = number.divided_by_power(result.exponent - precision);
  882. // FIXME: Can we do this without string conversion?
  883. auto digits = MUST_OR_THROW_OOM(result.number.to_string(vm));
  884. auto digit = digits.bytes_as_string_view().substring_view(digits.bytes_as_string_view().length() - 1);
  885. result.number = result.number.divided_by(10);
  886. if (mode == PreferredResult::GreaterThanNumber && digit.to_uint().value() != 0)
  887. result.number = result.number.plus(1);
  888. }
  889. result.rounded = result.number.multiplied_by_power(result.exponent - precision + 1);
  890. return result;
  891. }
  892. // 15.5.8 ToRawPrecision ( x, minPrecision, maxPrecision ), https://tc39.es/ecma402/#sec-torawprecision
  893. ThrowCompletionOr<RawFormatResult> to_raw_precision(VM& vm, MathematicalValue const& number, int min_precision, int max_precision, NumberFormat::UnsignedRoundingMode unsigned_rounding_mode)
  894. {
  895. RawFormatResult result {};
  896. // 1. Let p be maxPrecision.
  897. int precision = max_precision;
  898. int exponent = 0;
  899. // 2. If x = 0, then
  900. if (number.is_zero()) {
  901. // a. Let m be the String consisting of p occurrences of the code unit 0x0030 (DIGIT ZERO).
  902. result.formatted_string = TRY_OR_THROW_OOM(vm, String::repeated('0', precision));
  903. // b. Let e be 0.
  904. exponent = 0;
  905. // c. Let xFinal be 0.
  906. result.rounded_number = MathematicalValue { 0.0 };
  907. }
  908. // 3. Else,
  909. else {
  910. // a. Let n1 and e1 each be an integer and r1 a mathematical value, with r1 = ToRawPrecisionFn(n1, e1, p), such that r1 ≤ x and r1 is maximized.
  911. auto [number1, exponent1, rounded1] = MUST_OR_THROW_OOM(to_raw_precision_function(vm, number, precision, PreferredResult::LessThanNumber));
  912. // b. Let n2 and e2 each be an integer and r2 a mathematical value, with r2 = ToRawPrecisionFn(n2, e2, p), such that r2 ≥ x and r2 is minimized.
  913. auto [number2, exponent2, rounded2] = MUST_OR_THROW_OOM(to_raw_precision_function(vm, number, precision, PreferredResult::GreaterThanNumber));
  914. // c. Let r be ApplyUnsignedRoundingMode(x, r1, r2, unsignedRoundingMode).
  915. auto rounded = apply_unsigned_rounding_mode(number, rounded1, rounded2, unsigned_rounding_mode);
  916. MathematicalValue n;
  917. // d. If r is r1, then
  918. if (rounded == RoundingDecision::LowerValue) {
  919. // i. Let n be n1.
  920. n = move(number1);
  921. // ii. Let e be e1.
  922. exponent = exponent1;
  923. // iii. Let xFinal be r1.
  924. result.rounded_number = move(rounded1);
  925. }
  926. // e. Else,
  927. else {
  928. // i. Let n be n2.
  929. n = move(number2);
  930. // ii. Let e be e2.
  931. exponent = exponent2;
  932. // iii. Let xFinal be r2.
  933. result.rounded_number = move(rounded2);
  934. }
  935. // f. Let m be the String consisting of the digits of the decimal representation of n (in order, with no leading zeroes).
  936. result.formatted_string = MUST_OR_THROW_OOM(n.to_string(vm));
  937. }
  938. // 4. If e ≥ (p – 1), then
  939. if (exponent >= (precision - 1)) {
  940. // a. Set m to the string-concatenation of m and e - p + 1 occurrences of the code unit 0x0030 (DIGIT ZERO).
  941. result.formatted_string = TRY_OR_THROW_OOM(vm,
  942. String::formatted(
  943. "{}{}",
  944. result.formatted_string,
  945. TRY_OR_THROW_OOM(vm, String::repeated('0', exponent - precision + 1))));
  946. // b. Let int be e + 1.
  947. result.digits = exponent + 1;
  948. }
  949. // 5. Else if e ≥ 0, then
  950. else if (exponent >= 0) {
  951. // a. Set m to the string-concatenation of the first e + 1 code units of m, the code unit 0x002E (FULL STOP), and the remaining p - (e + 1) code units of m.
  952. result.formatted_string = TRY_OR_THROW_OOM(vm,
  953. String::formatted(
  954. "{}.{}",
  955. result.formatted_string.bytes_as_string_view().substring_view(0, exponent + 1),
  956. result.formatted_string.bytes_as_string_view().substring_view(exponent + 1)));
  957. // b. Let int be e + 1.
  958. result.digits = exponent + 1;
  959. }
  960. // 6. Else,
  961. else {
  962. // a. Assert: e < 0.
  963. // b. Set m to the string-concatenation of "0.", -(e + 1) occurrences of the code unit 0x0030 (DIGIT ZERO), and m.
  964. result.formatted_string = TRY_OR_THROW_OOM(vm,
  965. String::formatted(
  966. "0.{}{}",
  967. TRY_OR_THROW_OOM(vm, String::repeated('0', -1 * (exponent + 1))),
  968. result.formatted_string));
  969. // c. Let int be 1.
  970. result.digits = 1;
  971. }
  972. // 7. If m contains the code unit 0x002E (FULL STOP) and maxPrecision > minPrecision, then
  973. if (result.formatted_string.contains('.') && (max_precision > min_precision)) {
  974. // a. Let cut be maxPrecision – minPrecision.
  975. int cut = max_precision - min_precision;
  976. // Steps 8b-8c are implemented by cut_trailing_zeroes.
  977. result.formatted_string = TRY_OR_THROW_OOM(vm, cut_trailing_zeroes(result.formatted_string, cut));
  978. }
  979. // 8. Return the Record { [[FormattedString]]: m, [[RoundedNumber]]: xFinal, [[IntegerDigitsCount]]: int, [[RoundingMagnitude]]: e–p+1 }.
  980. result.rounding_magnitude = exponent - precision + 1;
  981. return result;
  982. }
  983. struct RawFixedResult {
  984. MathematicalValue number;
  985. MathematicalValue rounded;
  986. };
  987. // ToRawFixedFn, https://tc39.es/ecma402/#eqn-ToRawFixedFn
  988. static ThrowCompletionOr<RawFixedResult> to_raw_fixed_function(VM& vm, MathematicalValue const& number, int fraction, int rounding_increment, PreferredResult mode)
  989. {
  990. RawFixedResult result {};
  991. if (number.is_number()) {
  992. result.number = number.multiplied_by_power(fraction);
  993. switch (mode) {
  994. case PreferredResult::LessThanNumber:
  995. result.number = MathematicalValue { floor(result.number.as_number()) };
  996. break;
  997. case PreferredResult::GreaterThanNumber:
  998. result.number = MathematicalValue { ceil(result.number.as_number()) };
  999. break;
  1000. }
  1001. } else {
  1002. // NOTE: In order to round the BigInt to the proper precision, this computation is initially off by a
  1003. // factor of 10. This lets us inspect the ones digit and then round up if needed.
  1004. result.number = number.multiplied_by_power(fraction - 1);
  1005. // FIXME: Can we do this without string conversion?
  1006. auto digits = MUST_OR_THROW_OOM(result.number.to_string(vm));
  1007. auto digit = digits.bytes_as_string_view().substring_view(digits.bytes_as_string_view().length() - 1);
  1008. result.number = result.number.multiplied_by(10);
  1009. if (mode == PreferredResult::GreaterThanNumber && digit.to_uint().value() != 0)
  1010. result.number = result.number.plus(1);
  1011. }
  1012. while (!result.number.modulo_is_zero(rounding_increment)) {
  1013. switch (mode) {
  1014. case PreferredResult::LessThanNumber:
  1015. result.number = result.number.minus(1);
  1016. break;
  1017. case PreferredResult::GreaterThanNumber:
  1018. result.number = result.number.plus(1);
  1019. break;
  1020. }
  1021. }
  1022. result.rounded = result.number.divided_by_power(fraction);
  1023. return result;
  1024. }
  1025. // 15.5.9 ToRawFixed ( x, minInteger, minFraction, maxFraction ), https://tc39.es/ecma402/#sec-torawfixed
  1026. ThrowCompletionOr<RawFormatResult> to_raw_fixed(VM& vm, MathematicalValue const& number, int min_fraction, int max_fraction, int rounding_increment, NumberFormat::UnsignedRoundingMode unsigned_rounding_mode)
  1027. {
  1028. RawFormatResult result {};
  1029. // 1. Let f be maxFraction.
  1030. int fraction = max_fraction;
  1031. // 2. Let n1 be an integer and r1 a mathematical value, with r1 = ToRawFixedFn(n1, f), such that n1 modulo roundingIncrement = 0, r1 ≤ x, and r1 is maximized.
  1032. auto [number1, rounded1] = MUST_OR_THROW_OOM(to_raw_fixed_function(vm, number, fraction, rounding_increment, PreferredResult::LessThanNumber));
  1033. // 3. Let n2 be an integer and r2 a mathematical value, with r2 = ToRawFixedFn(n2, f), such that n2 modulo roundingIncrement = 0, r2 ≥ x, and r2 is minimized.
  1034. auto [number2, rounded2] = MUST_OR_THROW_OOM(to_raw_fixed_function(vm, number, fraction, rounding_increment, PreferredResult::GreaterThanNumber));
  1035. // 4. Let r be ApplyUnsignedRoundingMode(x, r1, r2, unsignedRoundingMode).
  1036. auto rounded = apply_unsigned_rounding_mode(number, rounded1, rounded2, unsigned_rounding_mode);
  1037. MathematicalValue n;
  1038. // 5. If r is r1, then
  1039. if (rounded == RoundingDecision::LowerValue) {
  1040. // a. Let n be n1.
  1041. n = move(number1);
  1042. // b. Let xFinal be r1.
  1043. result.rounded_number = move(rounded1);
  1044. }
  1045. // 6. Else,
  1046. else {
  1047. // a. Let n be n2.
  1048. n = move(number2);
  1049. // b. Let xFinal be r2.
  1050. result.rounded_number = move(rounded2);
  1051. }
  1052. // 7. If n = 0, let m be "0". Otherwise, let m be the String consisting of the digits of the decimal representation of n (in order, with no leading zeroes).
  1053. result.formatted_string = n.is_zero()
  1054. ? "0"_string
  1055. : MUST_OR_THROW_OOM(n.to_string(vm));
  1056. // 8. If f ≠ 0, then
  1057. if (fraction != 0) {
  1058. // a. Let k be the length of m.
  1059. auto decimals = result.formatted_string.bytes_as_string_view().length();
  1060. // b. If k ≤ f, then
  1061. if (decimals <= static_cast<size_t>(fraction)) {
  1062. // i. Let z be the String value consisting of f + 1 - k occurrences of the code unit 0x0030 (DIGIT ZERO).
  1063. auto zeroes = TRY_OR_THROW_OOM(vm, String::repeated('0', fraction + 1 - decimals));
  1064. // ii. Let m be the string-concatenation of z and m.
  1065. result.formatted_string = TRY_OR_THROW_OOM(vm, String::formatted("{}{}", zeroes, result.formatted_string));
  1066. // iii. Let k be f + 1.
  1067. decimals = fraction + 1;
  1068. }
  1069. // c. Let a be the first k - f code units of m, and let b be the remaining f code units of m.
  1070. auto a = result.formatted_string.bytes_as_string_view().substring_view(0, decimals - fraction);
  1071. auto b = result.formatted_string.bytes_as_string_view().substring_view(decimals - fraction, fraction);
  1072. // d. Let m be the string-concatenation of a, ".", and b.
  1073. result.formatted_string = TRY_OR_THROW_OOM(vm, String::formatted("{}.{}", a, b));
  1074. // e. Let int be the length of a.
  1075. result.digits = a.length();
  1076. }
  1077. // 9. Else, let int be the length of m.
  1078. else {
  1079. result.digits = result.formatted_string.bytes_as_string_view().length();
  1080. }
  1081. // 10. Let cut be maxFraction – minFraction.
  1082. int cut = max_fraction - min_fraction;
  1083. // Steps 11-12 are implemented by cut_trailing_zeroes.
  1084. result.formatted_string = TRY_OR_THROW_OOM(vm, cut_trailing_zeroes(result.formatted_string, cut));
  1085. // 13. Return the Record { [[FormattedString]]: m, [[RoundedNumber]]: xFinal, [[IntegerDigitsCount]]: int, [[RoundingMagnitude]]: –f }.
  1086. result.rounding_magnitude = -fraction;
  1087. return result;
  1088. }
  1089. enum class NumberCategory {
  1090. NegativeNonZero,
  1091. NegativeZero,
  1092. PositiveNonZero,
  1093. PositiveZero,
  1094. };
  1095. // 15.5.11 GetNumberFormatPattern ( numberFormat, x ), https://tc39.es/ecma402/#sec-getnumberformatpattern
  1096. ThrowCompletionOr<Optional<Variant<StringView, String>>> get_number_format_pattern(VM& vm, NumberFormat& number_format, MathematicalValue const& number, ::Locale::NumberFormat& found_pattern)
  1097. {
  1098. // 1. Let localeData be %NumberFormat%.[[LocaleData]].
  1099. // 2. Let dataLocale be numberFormat.[[DataLocale]].
  1100. // 3. Let dataLocaleData be localeData.[[<dataLocale>]].
  1101. // 4. Let patterns be dataLocaleData.[[patterns]].
  1102. // 5. Assert: patterns is a Record (see 15.3.3).
  1103. Optional<::Locale::NumberFormat> patterns;
  1104. // 6. Let style be numberFormat.[[Style]].
  1105. switch (number_format.style()) {
  1106. // 7. If style is "percent", then
  1107. case NumberFormat::Style::Percent:
  1108. // a. Let patterns be patterns.[[percent]].
  1109. patterns = TRY_OR_THROW_OOM(vm, ::Locale::get_standard_number_system_format(number_format.data_locale(), number_format.numbering_system(), ::Locale::StandardNumberFormatType::Percent));
  1110. break;
  1111. // 8. Else if style is "unit", then
  1112. case NumberFormat::Style::Unit: {
  1113. // a. Let unit be numberFormat.[[Unit]].
  1114. // b. Let unitDisplay be numberFormat.[[UnitDisplay]].
  1115. // c. Let patterns be patterns.[[unit]].
  1116. // d. If patterns doesn't have a field [[<unit>]], then
  1117. // i. Let unit be "fallback".
  1118. // e. Let patterns be patterns.[[<unit>]].
  1119. // f. Let patterns be patterns.[[<unitDisplay>]].
  1120. auto formats = TRY_OR_THROW_OOM(vm, ::Locale::get_unit_formats(number_format.data_locale(), number_format.unit(), number_format.unit_display()));
  1121. auto plurality = MUST_OR_THROW_OOM(resolve_plural(vm, number_format, ::Locale::PluralForm::Cardinal, number.to_value(vm)));
  1122. if (auto it = formats.find_if([&](auto& p) { return p.plurality == plurality.plural_category; }); it != formats.end())
  1123. patterns = move(*it);
  1124. break;
  1125. }
  1126. // 9. Else if style is "currency", then
  1127. case NumberFormat::Style::Currency:
  1128. // a. Let currency be numberFormat.[[Currency]].
  1129. // b. Let currencyDisplay be numberFormat.[[CurrencyDisplay]].
  1130. // c. Let currencySign be numberFormat.[[CurrencySign]].
  1131. // d. Let patterns be patterns.[[currency]].
  1132. // e. If patterns doesn't have a field [[<currency>]], then
  1133. // i. Let currency be "fallback".
  1134. // f. Let patterns be patterns.[[<currency>]].
  1135. // g. Let patterns be patterns.[[<currencyDisplay>]].
  1136. // h. Let patterns be patterns.[[<currencySign>]].
  1137. // Handling of other [[CurrencyDisplay]] options will occur after [[SignDisplay]].
  1138. if (number_format.currency_display() == NumberFormat::CurrencyDisplay::Name) {
  1139. auto formats = TRY_OR_THROW_OOM(vm, ::Locale::get_compact_number_system_formats(number_format.data_locale(), number_format.numbering_system(), ::Locale::CompactNumberFormatType::CurrencyUnit));
  1140. auto plurality = MUST_OR_THROW_OOM(resolve_plural(vm, number_format, ::Locale::PluralForm::Cardinal, number.to_value(vm)));
  1141. if (auto it = formats.find_if([&](auto& p) { return p.plurality == plurality.plural_category; }); it != formats.end()) {
  1142. patterns = move(*it);
  1143. break;
  1144. }
  1145. }
  1146. switch (number_format.currency_sign()) {
  1147. case NumberFormat::CurrencySign::Standard:
  1148. patterns = TRY_OR_THROW_OOM(vm, ::Locale::get_standard_number_system_format(number_format.data_locale(), number_format.numbering_system(), ::Locale::StandardNumberFormatType::Currency));
  1149. break;
  1150. case NumberFormat::CurrencySign::Accounting:
  1151. patterns = TRY_OR_THROW_OOM(vm, ::Locale::get_standard_number_system_format(number_format.data_locale(), number_format.numbering_system(), ::Locale::StandardNumberFormatType::Accounting));
  1152. break;
  1153. }
  1154. break;
  1155. // 10. Else,
  1156. case NumberFormat::Style::Decimal:
  1157. // a. Assert: style is "decimal".
  1158. // b. Let patterns be patterns.[[decimal]].
  1159. patterns = TRY_OR_THROW_OOM(vm, ::Locale::get_standard_number_system_format(number_format.data_locale(), number_format.numbering_system(), ::Locale::StandardNumberFormatType::Decimal));
  1160. break;
  1161. default:
  1162. VERIFY_NOT_REACHED();
  1163. }
  1164. if (!patterns.has_value())
  1165. return OptionalNone {};
  1166. NumberCategory category;
  1167. // 11. If x is negative-infinity, then
  1168. if (number.is_negative_infinity()) {
  1169. // a. Let category be negative-nonzero.
  1170. category = NumberCategory::NegativeNonZero;
  1171. }
  1172. // 12. Else if x is negative-zero, then
  1173. else if (number.is_negative_zero()) {
  1174. // a. Let category be negative-zero.
  1175. category = NumberCategory::NegativeZero;
  1176. }
  1177. // 13. Else if x is not-a-number, then
  1178. else if (number.is_nan()) {
  1179. // a. Let category be positive-zero.
  1180. category = NumberCategory::PositiveZero;
  1181. }
  1182. // 14. Else if x is positive-infinity, then
  1183. else if (number.is_positive_infinity()) {
  1184. // a. Let category be positive-nonzero.
  1185. category = NumberCategory::PositiveNonZero;
  1186. }
  1187. // 15. Else,
  1188. else {
  1189. // a. Assert: x is a mathematical value.
  1190. VERIFY(number.is_mathematical_value());
  1191. // b. If x < 0, then
  1192. if (number.is_negative()) {
  1193. // i. Let category be negative-nonzero.
  1194. category = NumberCategory::NegativeNonZero;
  1195. }
  1196. // c. Else if x > 0, then
  1197. else if (number.is_positive()) {
  1198. // i. Let category be positive-nonzero.
  1199. category = NumberCategory::PositiveNonZero;
  1200. }
  1201. // d. Else,
  1202. else {
  1203. // i. Let category be positive-zero.
  1204. category = NumberCategory::PositiveZero;
  1205. }
  1206. }
  1207. StringView pattern;
  1208. // 16. Let signDisplay be numberFormat.[[SignDisplay]].
  1209. switch (number_format.sign_display()) {
  1210. // 17. If signDisplay is "never", then
  1211. case NumberFormat::SignDisplay::Never:
  1212. // a. Let pattern be patterns.[[zeroPattern]].
  1213. pattern = patterns->zero_format;
  1214. break;
  1215. // 18. Else if signDisplay is "auto", then
  1216. case NumberFormat::SignDisplay::Auto:
  1217. // a. If category is positive-nonzero or positive-zero, then
  1218. if (category == NumberCategory::PositiveNonZero || category == NumberCategory::PositiveZero) {
  1219. // i. Let pattern be patterns.[[zeroPattern]].
  1220. pattern = patterns->zero_format;
  1221. }
  1222. // b. Else,
  1223. else {
  1224. // i. Let pattern be patterns.[[negativePattern]].
  1225. pattern = patterns->negative_format;
  1226. }
  1227. break;
  1228. // 19. Else if signDisplay is "always", then
  1229. case NumberFormat::SignDisplay::Always:
  1230. // a. If category is positive-nonzero or positive-zero, then
  1231. if (category == NumberCategory::PositiveNonZero || category == NumberCategory::PositiveZero) {
  1232. // i. Let pattern be patterns.[[positivePattern]].
  1233. pattern = patterns->positive_format;
  1234. }
  1235. // b. Else,
  1236. else {
  1237. // i. Let pattern be patterns.[[negativePattern]].
  1238. pattern = patterns->negative_format;
  1239. }
  1240. break;
  1241. // 20. Else if signDisplay is "exceptZero", then
  1242. case NumberFormat::SignDisplay::ExceptZero:
  1243. // a. If category is positive-zero or negative-zero, then
  1244. if (category == NumberCategory::PositiveZero || category == NumberCategory::NegativeZero) {
  1245. // i. Let pattern be patterns.[[zeroPattern]].
  1246. pattern = patterns->zero_format;
  1247. }
  1248. // b. Else if category is positive-nonzero, then
  1249. else if (category == NumberCategory::PositiveNonZero) {
  1250. // i. Let pattern be patterns.[[positivePattern]].
  1251. pattern = patterns->positive_format;
  1252. }
  1253. // c. Else,
  1254. else {
  1255. // i. Let pattern be patterns.[[negativePattern]].
  1256. pattern = patterns->negative_format;
  1257. }
  1258. break;
  1259. // 21. Else,
  1260. case NumberFormat::SignDisplay::Negative:
  1261. // a. Assert: signDisplay is "negative".
  1262. // b. If category is negative-nonzero, then
  1263. if (category == NumberCategory::NegativeNonZero) {
  1264. // i. Let pattern be patterns.[[negativePattern]].
  1265. pattern = patterns->negative_format;
  1266. }
  1267. // c. Else,
  1268. else {
  1269. // i. Let pattern be patterns.[[zeroPattern]].
  1270. pattern = patterns->zero_format;
  1271. }
  1272. break;
  1273. default:
  1274. VERIFY_NOT_REACHED();
  1275. }
  1276. found_pattern = patterns.release_value();
  1277. // Handling of steps 9b/9g: Depending on the currency display and the format pattern found above,
  1278. // we might need to mutate the format pattern to inject a space between the currency display and
  1279. // the currency number.
  1280. if (number_format.style() == NumberFormat::Style::Currency) {
  1281. auto modified_pattern = TRY_OR_THROW_OOM(vm, ::Locale::augment_currency_format_pattern(number_format.resolve_currency_display(), pattern));
  1282. if (modified_pattern.has_value())
  1283. return modified_pattern.release_value();
  1284. }
  1285. // 22. Return pattern.
  1286. return pattern;
  1287. }
  1288. // 15.5.12 GetNotationSubPattern ( numberFormat, exponent ), https://tc39.es/ecma402/#sec-getnotationsubpattern
  1289. ThrowCompletionOr<Optional<StringView>> get_notation_sub_pattern(VM& vm, NumberFormat& number_format, int exponent)
  1290. {
  1291. // 1. Let localeData be %NumberFormat%.[[LocaleData]].
  1292. // 2. Let dataLocale be numberFormat.[[DataLocale]].
  1293. // 3. Let dataLocaleData be localeData.[[<dataLocale>]].
  1294. // 4. Let notationSubPatterns be dataLocaleData.[[notationSubPatterns]].
  1295. // 5. Assert: notationSubPatterns is a Record (see 15.3.3).
  1296. // 6. Let notation be numberFormat.[[Notation]].
  1297. auto notation = number_format.notation();
  1298. // 7. If notation is "scientific" or notation is "engineering", then
  1299. if ((notation == NumberFormat::Notation::Scientific) || (notation == NumberFormat::Notation::Engineering)) {
  1300. // a. Return notationSubPatterns.[[scientific]].
  1301. auto notation_sub_patterns = TRY_OR_THROW_OOM(vm, ::Locale::get_standard_number_system_format(number_format.data_locale(), number_format.numbering_system(), ::Locale::StandardNumberFormatType::Scientific));
  1302. if (!notation_sub_patterns.has_value())
  1303. return OptionalNone {};
  1304. return notation_sub_patterns->zero_format;
  1305. }
  1306. // 8. Else if exponent is not 0, then
  1307. else if (exponent != 0) {
  1308. // a. Assert: notation is "compact".
  1309. VERIFY(notation == NumberFormat::Notation::Compact);
  1310. // b. Let compactDisplay be numberFormat.[[CompactDisplay]].
  1311. // c. Let compactPatterns be notationSubPatterns.[[compact]].[[<compactDisplay>]].
  1312. // d. Return compactPatterns.[[<exponent>]].
  1313. if (number_format.has_compact_format())
  1314. return number_format.compact_format().zero_format;
  1315. }
  1316. // 9. Else,
  1317. // a. Return "{number}".
  1318. return "{number}"sv;
  1319. }
  1320. // 15.5.13 ComputeExponent ( numberFormat, x ), https://tc39.es/ecma402/#sec-computeexponent
  1321. ThrowCompletionOr<int> compute_exponent(VM& vm, NumberFormat& number_format, MathematicalValue number)
  1322. {
  1323. // 1. If x = 0, then
  1324. if (number.is_zero()) {
  1325. // a. Return 0.
  1326. return 0;
  1327. }
  1328. // 2. If x < 0, then
  1329. if (number.is_negative()) {
  1330. // a. Let x = -x.
  1331. number.negate();
  1332. }
  1333. // 3. Let magnitude be the base 10 logarithm of x rounded down to the nearest integer.
  1334. int magnitude = MUST_OR_THROW_OOM(number.logarithmic_floor(vm));
  1335. // 4. Let exponent be ComputeExponentForMagnitude(numberFormat, magnitude).
  1336. int exponent = MUST_OR_THROW_OOM(compute_exponent_for_magnitude(vm, number_format, magnitude));
  1337. // 5. Let x be x × 10^(-exponent).
  1338. number = number.multiplied_by_power(-exponent);
  1339. // 6. Let formatNumberResult be FormatNumericToString(numberFormat, x).
  1340. auto format_number_result = MUST_OR_THROW_OOM(format_numeric_to_string(vm, number_format, move(number)));
  1341. // 7. If formatNumberResult.[[RoundedNumber]] = 0, then
  1342. if (format_number_result.rounded_number.is_zero()) {
  1343. // a. Return exponent.
  1344. return exponent;
  1345. }
  1346. // 8. Let newMagnitude be the base 10 logarithm of formatNumberResult.[[RoundedNumber]] rounded down to the nearest integer.
  1347. int new_magnitude = MUST_OR_THROW_OOM(format_number_result.rounded_number.logarithmic_floor(vm));
  1348. // 9. If newMagnitude is magnitude - exponent, then
  1349. if (new_magnitude == magnitude - exponent) {
  1350. // a. Return exponent.
  1351. return exponent;
  1352. }
  1353. // 10. Return ComputeExponentForMagnitude(numberFormat, magnitude + 1).
  1354. return MUST_OR_THROW_OOM(compute_exponent_for_magnitude(vm, number_format, magnitude + 1));
  1355. }
  1356. // 15.5.14 ComputeExponentForMagnitude ( numberFormat, magnitude ), https://tc39.es/ecma402/#sec-computeexponentformagnitude
  1357. ThrowCompletionOr<int> compute_exponent_for_magnitude(VM& vm, NumberFormat& number_format, int magnitude)
  1358. {
  1359. // 1. Let notation be numberFormat.[[Notation]].
  1360. switch (number_format.notation()) {
  1361. // 2. If notation is "standard", then
  1362. case NumberFormat::Notation::Standard:
  1363. // a. Return 0.
  1364. return 0;
  1365. // 3. Else if notation is "scientific", then
  1366. case NumberFormat::Notation::Scientific:
  1367. // a. Return magnitude.
  1368. return magnitude;
  1369. // 4. Else if notation is "engineering", then
  1370. case NumberFormat::Notation::Engineering: {
  1371. // a. Let thousands be the greatest integer that is not greater than magnitude / 3.
  1372. double thousands = floor(static_cast<double>(magnitude) / 3.0);
  1373. // b. Return thousands × 3.
  1374. return static_cast<int>(thousands) * 3;
  1375. }
  1376. // 5. Else,
  1377. case NumberFormat::Notation::Compact: {
  1378. // a. Assert: notation is "compact".
  1379. VERIFY(number_format.has_compact_display());
  1380. // 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.
  1381. // c. Return exponent.
  1382. Vector<::Locale::NumberFormat> format_rules;
  1383. if (number_format.style() == NumberFormat::Style::Currency)
  1384. format_rules = TRY_OR_THROW_OOM(vm, ::Locale::get_compact_number_system_formats(number_format.data_locale(), number_format.numbering_system(), ::Locale::CompactNumberFormatType::CurrencyShort));
  1385. else if (number_format.compact_display() == NumberFormat::CompactDisplay::Long)
  1386. format_rules = TRY_OR_THROW_OOM(vm, ::Locale::get_compact_number_system_formats(number_format.data_locale(), number_format.numbering_system(), ::Locale::CompactNumberFormatType::DecimalLong));
  1387. else
  1388. format_rules = TRY_OR_THROW_OOM(vm, ::Locale::get_compact_number_system_formats(number_format.data_locale(), number_format.numbering_system(), ::Locale::CompactNumberFormatType::DecimalShort));
  1389. ::Locale::NumberFormat const* best_number_format = nullptr;
  1390. for (auto const& format_rule : format_rules) {
  1391. if (format_rule.magnitude > magnitude)
  1392. break;
  1393. best_number_format = &format_rule;
  1394. }
  1395. if (best_number_format == nullptr)
  1396. return 0;
  1397. number_format.set_compact_format(*best_number_format);
  1398. return best_number_format->exponent;
  1399. }
  1400. default:
  1401. VERIFY_NOT_REACHED();
  1402. }
  1403. }
  1404. // 15.5.16 ToIntlMathematicalValue ( value ), https://tc39.es/ecma402/#sec-tointlmathematicalvalue
  1405. ThrowCompletionOr<MathematicalValue> to_intl_mathematical_value(VM& vm, Value value)
  1406. {
  1407. // 1. Let primValue be ? ToPrimitive(value, number).
  1408. auto primitive_value = TRY(value.to_primitive(vm, Value::PreferredType::Number));
  1409. // 2. If Type(primValue) is BigInt, return the mathematical value of primValue.
  1410. if (primitive_value.is_bigint())
  1411. return primitive_value.as_bigint().big_integer();
  1412. // FIXME: The remaining steps are being refactored into a new Runtime Semantic, StringIntlMV.
  1413. // We short-circuit some of these steps to avoid known pitfalls.
  1414. // See: https://github.com/tc39/proposal-intl-numberformat-v3/pull/82
  1415. if (!primitive_value.is_string()) {
  1416. auto number = TRY(primitive_value.to_number(vm));
  1417. return number.as_double();
  1418. }
  1419. // 3. If Type(primValue) is String,
  1420. // a. Let str be primValue.
  1421. auto string = primitive_value.as_string().utf8_string();
  1422. // Step 4 handled separately by the FIXME above.
  1423. // 5. If the grammar cannot interpret str as an expansion of StringNumericLiteral, return not-a-number.
  1424. // 6. Let mv be the MV, a mathematical value, of ? ToNumber(str), as described in 7.1.4.1.1.
  1425. auto mathematical_value = TRY(primitive_value.to_number(vm)).as_double();
  1426. // 7. If mv is 0 and the first non white space code point in str is -, return negative-zero.
  1427. if (mathematical_value == 0.0 && string.bytes_as_string_view().trim_whitespace(TrimMode::Left).starts_with('-'))
  1428. return MathematicalValue::Symbol::NegativeZero;
  1429. // 8. If mv is 10^10000 and str contains Infinity, return positive-infinity.
  1430. if (mathematical_value == pow(10, 10000) && string.contains("Infinity"sv))
  1431. return MathematicalValue::Symbol::PositiveInfinity;
  1432. // 9. If mv is -10^10000 and str contains Infinity, return negative-infinity.
  1433. if (mathematical_value == pow(-10, 10000) && string.contains("Infinity"sv))
  1434. return MathematicalValue::Symbol::NegativeInfinity;
  1435. // 10. Return mv.
  1436. return mathematical_value;
  1437. }
  1438. // 15.5.17 GetUnsignedRoundingMode ( roundingMode, isNegative ), https://tc39.es/ecma402/#sec-getunsignedroundingmode
  1439. NumberFormat::UnsignedRoundingMode get_unsigned_rounding_mode(NumberFormat::RoundingMode rounding_mode, bool is_negative)
  1440. {
  1441. // 1. If isNegative is true, return the specification type in the third column of Table 15 where the first column is roundingMode and the second column is "negative".
  1442. // 2. Else, return the specification type in the third column of Table 15 where the first column is roundingMode and the second column is "positive".
  1443. // Table 15: Conversion from rounding mode to unsigned rounding mode, https://tc39.es/ecma402/#table-intl-unsigned-rounding-modes
  1444. switch (rounding_mode) {
  1445. case NumberFormat::RoundingMode::Ceil:
  1446. return is_negative ? NumberFormat::UnsignedRoundingMode::Zero : NumberFormat::UnsignedRoundingMode::Infinity;
  1447. case NumberFormat::RoundingMode::Floor:
  1448. return is_negative ? NumberFormat::UnsignedRoundingMode::Infinity : NumberFormat::UnsignedRoundingMode::Zero;
  1449. case NumberFormat::RoundingMode::Expand:
  1450. return NumberFormat::UnsignedRoundingMode::Infinity;
  1451. case NumberFormat::RoundingMode::Trunc:
  1452. return NumberFormat::UnsignedRoundingMode::Zero;
  1453. case NumberFormat::RoundingMode::HalfCeil:
  1454. return is_negative ? NumberFormat::UnsignedRoundingMode::HalfZero : NumberFormat::UnsignedRoundingMode::HalfInfinity;
  1455. case NumberFormat::RoundingMode::HalfFloor:
  1456. return is_negative ? NumberFormat::UnsignedRoundingMode::HalfInfinity : NumberFormat::UnsignedRoundingMode::HalfZero;
  1457. case NumberFormat::RoundingMode::HalfExpand:
  1458. return NumberFormat::UnsignedRoundingMode::HalfInfinity;
  1459. case NumberFormat::RoundingMode::HalfTrunc:
  1460. return NumberFormat::UnsignedRoundingMode::HalfZero;
  1461. case NumberFormat::RoundingMode::HalfEven:
  1462. return NumberFormat::UnsignedRoundingMode::HalfEven;
  1463. default:
  1464. VERIFY_NOT_REACHED();
  1465. };
  1466. }
  1467. // 15.5.18 ApplyUnsignedRoundingMode ( x, r1, r2, unsignedRoundingMode ), https://tc39.es/ecma402/#sec-applyunsignedroundingmode
  1468. RoundingDecision apply_unsigned_rounding_mode(MathematicalValue const& x, MathematicalValue const& r1, MathematicalValue const& r2, NumberFormat::UnsignedRoundingMode unsigned_rounding_mode)
  1469. {
  1470. // 1. If x is equal to r1, return r1.
  1471. if (x.is_equal_to(r1))
  1472. return RoundingDecision::LowerValue;
  1473. // FIXME: We skip this assertion due floating point inaccuracies. For example, entering "1.2345"
  1474. // in the JS REPL results in "1.234499999999999", and may cause this assertion to fail.
  1475. //
  1476. // This should be resolved when the "Intl mathematical value" is implemented to support
  1477. // arbitrarily precise decimals.
  1478. // https://tc39.es/ecma402/#intl-mathematical-value
  1479. // 2. Assert: r1 < x < r2.
  1480. // 3. Assert: unsignedRoundingMode is not undefined.
  1481. // 4. If unsignedRoundingMode is zero, return r1.
  1482. if (unsigned_rounding_mode == NumberFormat::UnsignedRoundingMode::Zero)
  1483. return RoundingDecision::LowerValue;
  1484. // 5. If unsignedRoundingMode is infinity, return r2.
  1485. if (unsigned_rounding_mode == NumberFormat::UnsignedRoundingMode::Infinity)
  1486. return RoundingDecision::HigherValue;
  1487. // 6. Let d1 be x – r1.
  1488. auto d1 = x.minus(r1);
  1489. // 7. Let d2 be r2 – x.
  1490. auto d2 = r2.minus(x);
  1491. // 8. If d1 < d2, return r1.
  1492. if (d1.is_less_than(d2))
  1493. return RoundingDecision::LowerValue;
  1494. // 9. If d2 < d1, return r2.
  1495. if (d2.is_less_than(d1))
  1496. return RoundingDecision::HigherValue;
  1497. // 10. Assert: d1 is equal to d2.
  1498. VERIFY(d1.is_equal_to(d2));
  1499. // 11. If unsignedRoundingMode is half-zero, return r1.
  1500. if (unsigned_rounding_mode == NumberFormat::UnsignedRoundingMode::HalfZero)
  1501. return RoundingDecision::LowerValue;
  1502. // 12. If unsignedRoundingMode is half-infinity, return r2.
  1503. if (unsigned_rounding_mode == NumberFormat::UnsignedRoundingMode::HalfInfinity)
  1504. return RoundingDecision::HigherValue;
  1505. // 13. Assert: unsignedRoundingMode is half-even.
  1506. VERIFY(unsigned_rounding_mode == NumberFormat::UnsignedRoundingMode::HalfEven);
  1507. // 14. Let cardinality be (r1 / (r2 – r1)) modulo 2.
  1508. auto cardinality = r1.divided_by(r2.minus(r1));
  1509. // 15. If cardinality is 0, return r1.
  1510. if (cardinality.modulo_is_zero(2))
  1511. return RoundingDecision::LowerValue;
  1512. // 16. Return r2.
  1513. return RoundingDecision::HigherValue;
  1514. }
  1515. // 15.5.19 PartitionNumberRangePattern ( numberFormat, x, y ), https://tc39.es/ecma402/#sec-partitionnumberrangepattern
  1516. ThrowCompletionOr<Vector<PatternPartitionWithSource>> partition_number_range_pattern(VM& vm, NumberFormat& number_format, MathematicalValue start, MathematicalValue end)
  1517. {
  1518. // 1. If x is NaN or y is NaN, throw a RangeError exception.
  1519. if (start.is_nan())
  1520. return vm.throw_completion<RangeError>(ErrorType::NumberIsNaN, "start"sv);
  1521. if (end.is_nan())
  1522. return vm.throw_completion<RangeError>(ErrorType::NumberIsNaN, "end"sv);
  1523. // 2. Let result be a new empty List.
  1524. Vector<PatternPartitionWithSource> result;
  1525. // 3. Let xResult be ? PartitionNumberPattern(numberFormat, x).
  1526. auto raw_start_result = TRY(partition_number_pattern(vm, number_format, move(start)));
  1527. auto start_result = MUST_OR_THROW_OOM(PatternPartitionWithSource::create_from_parent_list(vm, move(raw_start_result)));
  1528. // 4. Let yResult be ? PartitionNumberPattern(numberFormat, y).
  1529. auto raw_end_result = TRY(partition_number_pattern(vm, number_format, move(end)));
  1530. auto end_result = MUST_OR_THROW_OOM(PatternPartitionWithSource::create_from_parent_list(vm, move(raw_end_result)));
  1531. // 5. If ! FormatNumeric(numberFormat, x) is equal to ! FormatNumeric(numberFormat, y), then
  1532. auto formatted_start = MUST_OR_THROW_OOM(format_numeric(vm, number_format, start));
  1533. auto formatted_end = MUST_OR_THROW_OOM(format_numeric(vm, number_format, end));
  1534. if (formatted_start == formatted_end) {
  1535. // a. Let appxResult be ? FormatApproximately(numberFormat, xResult).
  1536. auto approximate_result = TRY(format_approximately(vm, number_format, move(start_result)));
  1537. // b. For each r in appxResult, do
  1538. for (auto& result : approximate_result) {
  1539. // i. Set r.[[Source]] to "shared".
  1540. result.source = "shared"sv;
  1541. }
  1542. // c. Return appxResult.
  1543. return approximate_result;
  1544. }
  1545. // 6. For each element r in xResult, do
  1546. TRY_OR_THROW_OOM(vm, result.try_ensure_capacity(start_result.size()));
  1547. for (auto& start_part : start_result) {
  1548. // a. Append a new Record { [[Type]]: r.[[Type]], [[Value]]: r.[[Value]], [[Source]]: "startRange" } as the last element of result.
  1549. PatternPartitionWithSource part;
  1550. part.type = start_part.type;
  1551. part.value = move(start_part.value);
  1552. part.source = "startRange"sv;
  1553. result.unchecked_append(move(part));
  1554. }
  1555. // 7. Let rangeSeparator be an ILND String value used to separate two numbers.
  1556. auto range_separator_symbol = ::Locale::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), ::Locale::NumericSymbol::RangeSeparator).value_or("-"sv);
  1557. auto range_separator = TRY_OR_THROW_OOM(vm, ::Locale::augment_range_pattern(range_separator_symbol, result.last().value, end_result[0].value));
  1558. // 8. Append a new Record { [[Type]]: "literal", [[Value]]: rangeSeparator, [[Source]]: "shared" } element to result.
  1559. PatternPartitionWithSource part;
  1560. part.type = "literal"sv;
  1561. part.value = range_separator.has_value()
  1562. ? range_separator.release_value()
  1563. : TRY_OR_THROW_OOM(vm, String::from_utf8(range_separator_symbol));
  1564. part.source = "shared"sv;
  1565. TRY_OR_THROW_OOM(vm, result.try_append(move(part)));
  1566. // 9. For each element r in yResult, do
  1567. TRY_OR_THROW_OOM(vm, result.try_ensure_capacity(result.size() + end_result.size()));
  1568. for (auto& end_part : end_result) {
  1569. // a. Append a new Record { [[Type]]: r.[[Type]], [[Value]]: r.[[Value]], [[Source]]: "endRange" } as the last element of result.
  1570. PatternPartitionWithSource part;
  1571. part.type = end_part.type;
  1572. part.value = move(end_part.value);
  1573. part.source = "endRange"sv;
  1574. result.unchecked_append(move(part));
  1575. }
  1576. // 10. Return ! CollapseNumberRange(result).
  1577. return collapse_number_range(move(result));
  1578. }
  1579. // 15.5.20 FormatApproximately ( numberFormat, result ), https://tc39.es/ecma402/#sec-formatapproximately
  1580. ThrowCompletionOr<Vector<PatternPartitionWithSource>> format_approximately(VM& vm, NumberFormat& number_format, Vector<PatternPartitionWithSource> result)
  1581. {
  1582. // 1. Let approximatelySign be an ILND String value used to signify that a number is approximate.
  1583. auto approximately_sign = ::Locale::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), ::Locale::NumericSymbol::ApproximatelySign);
  1584. // 2. If approximatelySign is not empty, insert a new Record { [[Type]]: "approximatelySign", [[Value]]: approximatelySign } at an ILND index in result. For example, if numberFormat has [[Locale]] "en-US" and [[NumberingSystem]] "latn" and [[Style]] "decimal", the new Record might be inserted before the first element of result.
  1585. if (approximately_sign.has_value() && !approximately_sign->is_empty()) {
  1586. PatternPartitionWithSource partition;
  1587. partition.type = "approximatelySign"sv;
  1588. partition.value = TRY_OR_THROW_OOM(vm, String::from_utf8(*approximately_sign));
  1589. TRY_OR_THROW_OOM(vm, result.try_insert_before_matching(move(partition), [](auto const& part) {
  1590. return part.type.is_one_of("integer"sv, "decimal"sv, "plusSign"sv, "minusSign"sv, "percentSign"sv, "currency"sv);
  1591. }));
  1592. }
  1593. // 3. Return result.
  1594. return result;
  1595. }
  1596. // 15.5.21 CollapseNumberRange ( result ), https://tc39.es/ecma402/#sec-collapsenumberrange
  1597. Vector<PatternPartitionWithSource> collapse_number_range(Vector<PatternPartitionWithSource> result)
  1598. {
  1599. // Returning result unmodified is guaranteed to be a correct implementation of CollapseNumberRange.
  1600. return result;
  1601. }
  1602. // 15.5.22 FormatNumericRange ( numberFormat, x, y ), https://tc39.es/ecma402/#sec-formatnumericrange
  1603. ThrowCompletionOr<String> format_numeric_range(VM& vm, NumberFormat& number_format, MathematicalValue start, MathematicalValue end)
  1604. {
  1605. // 1. Let parts be ? PartitionNumberRangePattern(numberFormat, x, y).
  1606. auto parts = TRY(partition_number_range_pattern(vm, number_format, move(start), move(end)));
  1607. // 2. Let result be the empty String.
  1608. ThrowableStringBuilder result(vm);
  1609. // 3. For each part in parts, do
  1610. for (auto& part : parts) {
  1611. // a. Set result to the string-concatenation of result and part.[[Value]].
  1612. TRY(result.append(part.value));
  1613. }
  1614. // 4. Return result.
  1615. return result.to_string();
  1616. }
  1617. // 15.5.23 FormatNumericRangeToParts ( numberFormat, x, y ), https://tc39.es/ecma402/#sec-formatnumericrangetoparts
  1618. ThrowCompletionOr<Array*> format_numeric_range_to_parts(VM& vm, NumberFormat& number_format, MathematicalValue start, MathematicalValue end)
  1619. {
  1620. auto& realm = *vm.current_realm();
  1621. // 1. Let parts be ? PartitionNumberRangePattern(numberFormat, x, y).
  1622. auto parts = TRY(partition_number_range_pattern(vm, number_format, move(start), move(end)));
  1623. // 2. Let result be ! ArrayCreate(0).
  1624. auto result = MUST(Array::create(realm, 0));
  1625. // 3. Let n be 0.
  1626. size_t n = 0;
  1627. // 4. For each Record { [[Type]], [[Value]] } part in parts, do
  1628. for (auto& part : parts) {
  1629. // a. Let O be OrdinaryObjectCreate(%Object.prototype%).
  1630. auto object = Object::create(realm, realm.intrinsics().object_prototype());
  1631. // b. Perform ! CreateDataPropertyOrThrow(O, "type", part.[[Type]]).
  1632. MUST(object->create_data_property_or_throw(vm.names.type, PrimitiveString::create(vm, part.type)));
  1633. // c. Perform ! CreateDataPropertyOrThrow(O, "value", part.[[Value]]).
  1634. MUST(object->create_data_property_or_throw(vm.names.value, PrimitiveString::create(vm, move(part.value))));
  1635. // d. Perform ! CreateDataPropertyOrThrow(O, "source", part.[[Source]]).
  1636. MUST(object->create_data_property_or_throw(vm.names.source, PrimitiveString::create(vm, part.source)));
  1637. // e. Perform ! CreateDataPropertyOrThrow(result, ! ToString(n), O).
  1638. MUST(result->create_data_property_or_throw(n, object));
  1639. // f. Increment n by 1.
  1640. ++n;
  1641. }
  1642. // 5. Return result.
  1643. return result.ptr();
  1644. }
  1645. }