NumberFormat.cpp 84 KB

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