DurationFormat.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  1. /*
  2. * Copyright (c) 2022, Idan Horowitz <idan.horowitz@serenityos.org>
  3. * Copyright (c) 2022-2023, Tim Flynn <trflynn89@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/StringBuilder.h>
  8. #include <LibJS/Runtime/AbstractOperations.h>
  9. #include <LibJS/Runtime/GlobalObject.h>
  10. #include <LibJS/Runtime/Intl/DurationFormat.h>
  11. #include <LibJS/Runtime/Intl/ListFormat.h>
  12. #include <LibJS/Runtime/Intl/ListFormatConstructor.h>
  13. #include <LibJS/Runtime/Intl/NumberFormatConstructor.h>
  14. #include <LibJS/Runtime/Intl/PluralRules.h>
  15. #include <LibJS/Runtime/Intl/PluralRulesConstructor.h>
  16. #include <LibJS/Runtime/Intl/RelativeTimeFormat.h>
  17. #include <LibJS/Runtime/Temporal/AbstractOperations.h>
  18. #include <LibJS/Runtime/ValueInlines.h>
  19. namespace JS::Intl {
  20. JS_DEFINE_ALLOCATOR(DurationFormat);
  21. // 1 DurationFormat Objects, https://tc39.es/proposal-intl-duration-format/#durationformat-objects
  22. DurationFormat::DurationFormat(Object& prototype)
  23. : Object(ConstructWithPrototypeTag::Tag, prototype)
  24. {
  25. }
  26. DurationFormat::Style DurationFormat::style_from_string(StringView style)
  27. {
  28. if (style == "long"sv)
  29. return Style::Long;
  30. if (style == "short"sv)
  31. return Style::Short;
  32. if (style == "narrow"sv)
  33. return Style::Narrow;
  34. if (style == "digital"sv)
  35. return Style::Digital;
  36. VERIFY_NOT_REACHED();
  37. }
  38. StringView DurationFormat::style_to_string(Style style)
  39. {
  40. switch (style) {
  41. case Style::Long:
  42. return "long"sv;
  43. case Style::Short:
  44. return "short"sv;
  45. case Style::Narrow:
  46. return "narrow"sv;
  47. case Style::Digital:
  48. return "digital"sv;
  49. default:
  50. VERIFY_NOT_REACHED();
  51. }
  52. }
  53. DurationFormat::ValueStyle DurationFormat::date_style_from_string(StringView date_style)
  54. {
  55. if (date_style == "long"sv)
  56. return ValueStyle::Long;
  57. if (date_style == "short"sv)
  58. return ValueStyle::Short;
  59. if (date_style == "narrow"sv)
  60. return ValueStyle::Narrow;
  61. VERIFY_NOT_REACHED();
  62. }
  63. DurationFormat::ValueStyle DurationFormat::time_style_from_string(StringView time_style)
  64. {
  65. if (time_style == "long"sv)
  66. return ValueStyle::Long;
  67. if (time_style == "short"sv)
  68. return ValueStyle::Short;
  69. if (time_style == "narrow"sv)
  70. return ValueStyle::Narrow;
  71. if (time_style == "numeric"sv)
  72. return ValueStyle::Numeric;
  73. if (time_style == "2-digit"sv)
  74. return ValueStyle::TwoDigit;
  75. VERIFY_NOT_REACHED();
  76. }
  77. DurationFormat::ValueStyle DurationFormat::sub_second_style_from_string(StringView sub_second_style)
  78. {
  79. if (sub_second_style == "long"sv)
  80. return ValueStyle::Long;
  81. if (sub_second_style == "short"sv)
  82. return ValueStyle::Short;
  83. if (sub_second_style == "narrow"sv)
  84. return ValueStyle::Narrow;
  85. if (sub_second_style == "numeric"sv)
  86. return ValueStyle::Numeric;
  87. VERIFY_NOT_REACHED();
  88. }
  89. DurationFormat::Display DurationFormat::display_from_string(StringView display)
  90. {
  91. if (display == "auto"sv)
  92. return Display::Auto;
  93. if (display == "always"sv)
  94. return Display::Always;
  95. VERIFY_NOT_REACHED();
  96. }
  97. StringView DurationFormat::value_style_to_string(ValueStyle value_style)
  98. {
  99. switch (value_style) {
  100. case ValueStyle::Long:
  101. return "long"sv;
  102. case ValueStyle::Short:
  103. return "short"sv;
  104. case ValueStyle::Narrow:
  105. return "narrow"sv;
  106. case ValueStyle::Numeric:
  107. return "numeric"sv;
  108. case ValueStyle::TwoDigit:
  109. return "2-digit"sv;
  110. default:
  111. VERIFY_NOT_REACHED();
  112. }
  113. }
  114. StringView DurationFormat::display_to_string(Display display)
  115. {
  116. switch (display) {
  117. case Display::Auto:
  118. return "auto"sv;
  119. case Display::Always:
  120. return "always"sv;
  121. default:
  122. VERIFY_NOT_REACHED();
  123. }
  124. }
  125. // 1.1.3 ToDurationRecord ( input ), https://tc39.es/proposal-intl-duration-format/#sec-todurationrecord
  126. ThrowCompletionOr<Temporal::DurationRecord> to_duration_record(VM& vm, Value input)
  127. {
  128. // 1. If Type(input) is not Object, then
  129. if (!input.is_object()) {
  130. // a. If Type(input) is String, throw a RangeError exception.
  131. if (input.is_string())
  132. return vm.throw_completion<RangeError>(ErrorType::NotAnObject, input);
  133. // b. Throw a TypeError exception.
  134. return vm.throw_completion<TypeError>(ErrorType::NotAnObject, input);
  135. }
  136. auto& input_object = input.as_object();
  137. // 2. Let result be a new Duration Record with each field set to 0.
  138. Temporal::DurationRecord result = {};
  139. bool any_defined = false;
  140. auto set_duration_record_value = [&](auto const& name, auto& value_slot) -> ThrowCompletionOr<void> {
  141. auto value = TRY(input_object.get(name));
  142. if (!value.is_undefined()) {
  143. value_slot = TRY(Temporal::to_integer_if_integral(vm, value, ErrorType::TemporalInvalidDurationPropertyValueNonIntegral, name, value));
  144. any_defined = true;
  145. }
  146. return {};
  147. };
  148. // 3. Let days be ? Get(input, "days").
  149. // 4. If days is not undefined, set result.[[Days]] to ? ToIntegerIfIntegral(days).
  150. TRY(set_duration_record_value(vm.names.days, result.days));
  151. // 5. Let hours be ? Get(input, "hours").
  152. // 6. If hours is not undefined, set result.[[Hours]] to ? ToIntegerIfIntegral(hours).
  153. TRY(set_duration_record_value(vm.names.hours, result.hours));
  154. // 7. Let microseconds be ? Get(input, "microseconds").
  155. // 8. If microseconds is not undefined, set result.[[Microseconds]] to ? ToIntegerIfIntegral(microseconds).
  156. TRY(set_duration_record_value(vm.names.microseconds, result.microseconds));
  157. // 9. Let milliseconds be ? Get(input, "milliseconds").
  158. // 10. If milliseconds is not undefined, set result.[[Milliseconds]] to ? ToIntegerIfIntegral(milliseconds).
  159. TRY(set_duration_record_value(vm.names.milliseconds, result.milliseconds));
  160. // 11. Let minutes be ? Get(input, "minutes").
  161. // 12. If minutes is not undefined, set result.[[Minutes]] to ? ToIntegerIfIntegral(minutes).
  162. TRY(set_duration_record_value(vm.names.minutes, result.minutes));
  163. // 13. Let months be ? Get(input, "months").
  164. // 14. If months is not undefined, set result.[[Months]] to ? ToIntegerIfIntegral(months).
  165. TRY(set_duration_record_value(vm.names.months, result.months));
  166. // 15. Let nanoseconds be ? Get(input, "nanoseconds").
  167. // 16. If nanoseconds is not undefined, set result.[[Nanoseconds]] to ? ToIntegerIfIntegral(nanoseconds).
  168. TRY(set_duration_record_value(vm.names.nanoseconds, result.nanoseconds));
  169. // 17. Let seconds be ? Get(input, "seconds").
  170. // 18. If seconds is not undefined, set result.[[Seconds]] to ? ToIntegerIfIntegral(seconds).
  171. TRY(set_duration_record_value(vm.names.seconds, result.seconds));
  172. // 19. Let weeks be ? Get(input, "weeks").
  173. // 20. If weeks is not undefined, set result.[[Weeks]] to ? ToIntegerIfIntegral(weeks).
  174. TRY(set_duration_record_value(vm.names.weeks, result.weeks));
  175. // 21. Let years be ? Get(input, "years").
  176. // 22. If years is not undefined, set result.[[Years]] to ? ToIntegerIfIntegral(years).
  177. TRY(set_duration_record_value(vm.names.years, result.years));
  178. // 23. If years, months, weeks, days, hours, minutes, seconds, milliseconds, microseconds, and nanoseconds are all undefined, throw a TypeError exception.
  179. if (!any_defined)
  180. return vm.throw_completion<TypeError>(ErrorType::TemporalInvalidDurationLikeObject);
  181. // 24. If IsValidDurationRecord(result) is false, throw a RangeError exception.
  182. if (!is_valid_duration_record(result))
  183. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidDurationLikeObject);
  184. // 25. Return result.
  185. return result;
  186. }
  187. // 1.1.4 DurationRecordSign ( record ), https://tc39.es/proposal-intl-duration-format/#sec-durationrecordsign
  188. i8 duration_record_sign(Temporal::DurationRecord const& record)
  189. {
  190. // 1. For each row of Table 1, except the header row, in table order, do
  191. for (auto const& duration_instances_component : duration_instances_components) {
  192. // a. Let valueSlot be the Value Slot value of the current row.
  193. auto value_slot = duration_instances_component.value_slot;
  194. // b. Let v be record.[[<valueSlot>]].
  195. auto value = record.*value_slot;
  196. // c. If v < 0, return -1.
  197. if (value < 0)
  198. return -1;
  199. // d. If v > 0, return 1.
  200. if (value > 0)
  201. return 1;
  202. }
  203. // 2. Return 0.
  204. return 0;
  205. }
  206. // 1.1.5 IsValidDurationRecord ( record ), https://tc39.es/proposal-intl-duration-format/#sec-isvaliddurationrecord
  207. bool is_valid_duration_record(Temporal::DurationRecord const& record)
  208. {
  209. // 1. Let sign be DurationRecordSign(record).
  210. auto sign = duration_record_sign(record);
  211. // 2. For each row of Table 1, except the header row, in table order, do
  212. for (auto const& duration_instances_component : duration_instances_components) {
  213. // a. Let valueSlot be the Value Slot value of the current row.
  214. auto value_slot = duration_instances_component.value_slot;
  215. // b. Let v be record.[[<valueSlot>]].
  216. auto value = record.*value_slot;
  217. // c. Assert: 𝔽(v) is finite.
  218. VERIFY(isfinite(value));
  219. // d. If v < 0 and sign > 0, return false.
  220. if (value < 0 && sign > 0)
  221. return false;
  222. // e. If v > 0 and sign < 0, return false.
  223. if (value > 0 && sign < 0)
  224. return false;
  225. }
  226. // 3. Return true.
  227. return true;
  228. }
  229. // 1.1.6 GetDurationUnitOptions ( unit, options, baseStyle, stylesList, digitalBase, prevStyle ), https://tc39.es/proposal-intl-duration-format/#sec-getdurationunitoptions
  230. ThrowCompletionOr<DurationUnitOptions> get_duration_unit_options(VM& vm, String const& unit, Object const& options, StringView base_style, ReadonlySpan<StringView> styles_list, StringView digital_base, StringView previous_style)
  231. {
  232. // 1. Let style be ? GetOption(options, unit, string, stylesList, undefined).
  233. auto style_value = TRY(get_option(vm, options, unit.to_byte_string(), OptionType::String, styles_list, Empty {}));
  234. // 2. Let displayDefault be "always".
  235. auto display_default = "always"sv;
  236. StringView style;
  237. // 3. If style is undefined, then
  238. if (style_value.is_undefined()) {
  239. // a. If baseStyle is "digital", then
  240. if (base_style == "digital"sv) {
  241. // i. If unit is not one of "hours", "minutes", or "seconds", then
  242. if (!unit.is_one_of("hours"sv, "minutes"sv, "seconds"sv)) {
  243. // 1. Set displayDefault to "auto".
  244. display_default = "auto"sv;
  245. }
  246. // ii. Set style to digitalBase.
  247. style = digital_base;
  248. }
  249. // b. Else,
  250. else {
  251. // i. Set displayDefault to "auto".
  252. display_default = "auto"sv;
  253. // ii. If prevStyle is "numeric" or "2-digit", then
  254. if (previous_style == "numeric"sv || previous_style == "2-digit"sv) {
  255. // 1. Set style to "numeric".
  256. style = "numeric"sv;
  257. }
  258. // iii. Else,
  259. else {
  260. // 1. Set style to baseStyle.
  261. style = base_style;
  262. }
  263. }
  264. } else {
  265. style = style_value.as_string().utf8_string_view();
  266. }
  267. // 4. Let displayField be the string-concatenation of unit and "Display".
  268. auto display_field = MUST(String::formatted("{}Display", unit));
  269. // 5. Let display be ? GetOption(options, displayField, string, « "auto", "always" », displayDefault).
  270. auto display = TRY(get_option(vm, options, display_field.to_byte_string(), OptionType::String, { "auto"sv, "always"sv }, display_default));
  271. // 6. If prevStyle is "numeric" or "2-digit", then
  272. if (previous_style == "numeric"sv || previous_style == "2-digit"sv) {
  273. // a. If style is not "numeric" or "2-digit", then
  274. if (style != "numeric"sv && style != "2-digit"sv) {
  275. // i. Throw a RangeError exception.
  276. return vm.throw_completion<RangeError>(ErrorType::IntlNonNumericOr2DigitAfterNumericOr2Digit);
  277. }
  278. // b. Else if unit is "minutes" or "seconds", then
  279. else if (unit == "minutes"sv || unit == "seconds"sv) {
  280. // i. Set style to "2-digit".
  281. style = "2-digit"sv;
  282. }
  283. }
  284. // 7. Return the Record { [[Style]]: style, [[Display]]: display }.
  285. return DurationUnitOptions { .style = MUST(String::from_utf8(style)), .display = display.as_string().utf8_string() };
  286. }
  287. // 1.1.7 PartitionDurationFormatPattern ( durationFormat, duration ), https://tc39.es/proposal-intl-duration-format/#sec-partitiondurationformatpattern
  288. Vector<PatternPartition> partition_duration_format_pattern(VM& vm, DurationFormat const& duration_format, Temporal::DurationRecord const& duration)
  289. {
  290. auto& realm = *vm.current_realm();
  291. // 1. Let result be a new empty List.
  292. Vector<PatternPartition> result;
  293. // 2. Let done be false.
  294. bool done = false;
  295. // 3. While done is false, repeat for each row in Table 1 in order, except the header row:
  296. for (size_t i = 0; !done && i < duration_instances_components.size(); ++i) {
  297. auto const& duration_instances_component = duration_instances_components[i];
  298. // a. Let styleSlot be the Style Slot value.
  299. auto style_slot = duration_instances_component.get_style_slot;
  300. // b. Let displaySlot be the Display Slot value.
  301. auto display_slot = duration_instances_component.get_display_slot;
  302. // c. Let valueSlot be the Value Slot value.
  303. auto value_slot = duration_instances_component.value_slot;
  304. // d. Let unit be the Unit value.
  305. auto unit = duration_instances_component.unit;
  306. // e. Let numberFormatUnit be the NumberFormat Unit value.
  307. auto number_format_unit = duration_instances_component.number_format_unit;
  308. // f. Let style be durationFormat.[[<styleSlot>]].
  309. auto style = (duration_format.*style_slot)();
  310. // g. Let display be durationFormat.[[<displaySlot>]].
  311. auto display = (duration_format.*display_slot)();
  312. // h. Let value be duration.[[<valueSlot>]].
  313. auto value = duration.*value_slot;
  314. // i. Let nfOpts be OrdinaryObjectCreate(null).
  315. auto number_format_options = Object::create(realm, nullptr);
  316. // j. If unit is "seconds", "milliseconds", or "microseconds", then
  317. if (unit.is_one_of("seconds"sv, "milliseconds"sv, "microseconds"sv)) {
  318. DurationFormat::ValueStyle next_style;
  319. // i. If unit is "seconds", then
  320. if (unit == "seconds"sv) {
  321. // 1. Let nextStyle be durationFormat.[[MillisecondsStyle]].
  322. next_style = duration_format.milliseconds_style();
  323. }
  324. // ii. Else if unit is "milliseconds", then
  325. else if (unit == "milliseconds"sv) {
  326. // 1. Let nextStyle be durationFormat.[[MicrosecondsStyle]].
  327. next_style = duration_format.microseconds_style();
  328. }
  329. // iii. Else,
  330. else {
  331. // 1. Let nextStyle be durationFormat.[[NanosecondsStyle]].
  332. next_style = duration_format.nanoseconds_style();
  333. }
  334. // iv. If nextStyle is "numeric", then
  335. if (next_style == DurationFormat::ValueStyle::Numeric) {
  336. // 1. If unit is "seconds", then
  337. if (unit == "seconds"sv) {
  338. // a. Set value to value + duration.[[Milliseconds]] / 10^3 + duration.[[Microseconds]] / 10^6 + duration.[[Nanoseconds]] / 10^9.
  339. value += duration.milliseconds / 1'000.0 + duration.microseconds / 1'000'000.0 + duration.nanoseconds / 1'000'000'000.0;
  340. }
  341. // 2. Else if unit is "milliseconds", then
  342. else if (unit == "milliseconds"sv) {
  343. // a. Set value to value + duration.[[Microseconds]] / 10^3 + duration.[[Nanoseconds]] / 10^6.
  344. value += duration.microseconds / 1'000.0 + duration.nanoseconds / 1'000'000.0;
  345. }
  346. // 3. Else,
  347. else {
  348. // a. Set value to value + duration.[[Nanoseconds]] / 10^3.
  349. value += duration.nanoseconds / 1'000.0;
  350. }
  351. // 4. Perform ! CreateDataPropertyOrThrow(nfOpts, "maximumFractionDigits", durationFormat.[[FractionalDigits]]).
  352. MUST(number_format_options->create_data_property_or_throw(vm.names.maximumFractionDigits, duration_format.has_fractional_digits() ? Value(duration_format.fractional_digits()) : js_undefined()));
  353. // 5. Perform ! CreateDataPropertyOrThrow(nfOpts, "minimumFractionDigits", durationFormat.[[FractionalDigits]]).
  354. MUST(number_format_options->create_data_property_or_throw(vm.names.minimumFractionDigits, duration_format.has_fractional_digits() ? Value(duration_format.fractional_digits()) : js_undefined()));
  355. // 6. Set done to true.
  356. done = true;
  357. }
  358. }
  359. // k. If style is "2-digit", then
  360. if (style == DurationFormat::ValueStyle::TwoDigit) {
  361. // i. Perform ! CreateDataPropertyOrThrow(nfOpts, "minimumIntegerDigits", 2𝔽).
  362. MUST(number_format_options->create_data_property_or_throw(vm.names.minimumIntegerDigits, Value(2)));
  363. }
  364. // l. If value is not 0 or display is not "auto", then
  365. if (value != 0.0 || display != DurationFormat::Display::Auto) {
  366. // i. If style is "2-digit" or "numeric", then
  367. if (style == DurationFormat::ValueStyle::TwoDigit || style == DurationFormat::ValueStyle::Numeric) {
  368. // 1. Let nf be ! Construct(%NumberFormat%, « durationFormat.[[Locale]], nfOpts »).
  369. auto* number_format = static_cast<NumberFormat*>(MUST(construct(vm, realm.intrinsics().intl_number_format_constructor(), PrimitiveString::create(vm, duration_format.locale()), number_format_options)).ptr());
  370. // 2. Let dataLocale be durationFormat.[[DataLocale]].
  371. auto const& data_locale = duration_format.data_locale();
  372. // 3. Let dataLocaleData be %DurationFormat%.[[LocaleData]].[[<dataLocale>]].
  373. // 4. Let num be ! FormatNumeric(nf, 𝔽(value)).
  374. auto number = format_numeric(vm, *number_format, MathematicalValue(value));
  375. // 5. Append the new Record { [[Type]]: unit, [[Value]]: num} to the end of result.
  376. result.append({ unit, move(number) });
  377. // 6. If unit is "hours" or "minutes", then
  378. if (unit.is_one_of("hours"sv, "minutes"sv)) {
  379. double next_value = 0.0;
  380. DurationFormat::Display next_display;
  381. // a. If unit is "hours", then
  382. if (unit == "hours"sv) {
  383. // i. Let nextValue be duration.[[Minutes]].
  384. next_value = duration.minutes;
  385. // ii. Let nextDisplay be durationFormat.[[MinutesDisplay]].
  386. next_display = duration_format.minutes_display();
  387. }
  388. // b. Else,
  389. else {
  390. // i. Let nextValue be duration.[[Seconds]].
  391. next_value = duration.seconds;
  392. // ii. Let nextDisplay be durationFormat.[[SecondsDisplay]].
  393. next_display = duration_format.seconds_display();
  394. // iii. If durationFormat.[[MillisecondsStyle]] is "numeric", then
  395. if (duration_format.milliseconds_style() == DurationFormat::ValueStyle::Numeric) {
  396. // i. Set nextValue to nextValue + duration.[[Milliseconds]] / 10^3 + duration.[[Microseconds]] / 10^6 + duration.[[Nanoseconds]] / 10^9.
  397. next_value += duration.milliseconds / 1'000.0 + duration.microseconds / 1'000'000.0 + duration.nanoseconds / 1'000'000'000.0;
  398. }
  399. }
  400. // c. If nextValue is not 0 or nextDisplay is not "auto", then
  401. if (next_value != 0.0 || next_display != DurationFormat::Display::Auto) {
  402. // i. Let separator be dataLocaleData.[[formats]].[[digital]].[[separator]].
  403. auto separator = ::Locale::get_number_system_symbol(data_locale, duration_format.numbering_system(), ::Locale::NumericSymbol::TimeSeparator).value_or(":"sv);
  404. // ii. Append the new Record { [[Type]]: "literal", [[Value]]: separator} to the end of result.
  405. result.append({ "literal"sv, MUST(String::from_utf8(separator)) });
  406. }
  407. }
  408. }
  409. // ii. Else,
  410. else {
  411. // 1. Perform ! CreateDataPropertyOrThrow(nfOpts, "style", "unit").
  412. MUST(number_format_options->create_data_property_or_throw(vm.names.style, PrimitiveString::create(vm, "unit"_string)));
  413. // 2. Perform ! CreateDataPropertyOrThrow(nfOpts, "unit", numberFormatUnit).
  414. MUST(number_format_options->create_data_property_or_throw(vm.names.unit, PrimitiveString::create(vm, number_format_unit)));
  415. // 3. Perform ! CreateDataPropertyOrThrow(nfOpts, "unitDisplay", style).
  416. auto unicode_style = ::Locale::style_to_string(static_cast<::Locale::Style>(style));
  417. MUST(number_format_options->create_data_property_or_throw(vm.names.unitDisplay, PrimitiveString::create(vm, unicode_style)));
  418. // 4. Let nf be ! Construct(%NumberFormat%, « durationFormat.[[Locale]], nfOpts »).
  419. auto* number_format = static_cast<NumberFormat*>(MUST(construct(vm, realm.intrinsics().intl_number_format_constructor(), PrimitiveString::create(vm, duration_format.locale()), number_format_options)).ptr());
  420. // 5. Let parts be ! PartitionNumberPattern(nf, 𝔽(value)).
  421. auto parts = partition_number_pattern(vm, *number_format, MathematicalValue(value));
  422. // 6. Let concat be an empty String.
  423. StringBuilder concat;
  424. // 7. For each Record { [[Type]], [[Value]], [[Unit]] } part in parts, do
  425. for (auto const& part : parts) {
  426. // a. Set concat to the string-concatenation of concat and part.[[Value]].
  427. concat.append(part.value);
  428. }
  429. // 8. Append the new Record { [[Type]]: unit, [[Value]]: concat } to the end of result.
  430. result.append({ unit, MUST(concat.to_string()) });
  431. }
  432. }
  433. }
  434. // 4. Let lfOpts be OrdinaryObjectCreate(null).
  435. auto list_format_options = Object::create(realm, nullptr);
  436. // 5. Perform ! CreateDataPropertyOrThrow(lfOpts, "type", "unit").
  437. MUST(list_format_options->create_data_property_or_throw(vm.names.type, PrimitiveString::create(vm, "unit"_string)));
  438. // 6. Let listStyle be durationFormat.[[Style]].
  439. auto list_style = duration_format.style();
  440. // 7. If listStyle is "digital", then
  441. if (list_style == DurationFormat::Style::Digital) {
  442. // a. Set listStyle to "short".
  443. list_style = DurationFormat::Style::Short;
  444. }
  445. auto unicode_list_style = ::Locale::style_to_string(static_cast<::Locale::Style>(list_style));
  446. // 8. Perform ! CreateDataPropertyOrThrow(lfOpts, "style", listStyle).
  447. MUST(list_format_options->create_data_property_or_throw(vm.names.style, PrimitiveString::create(vm, unicode_list_style)));
  448. // 9. Let lf be ! Construct(%ListFormat%, « durationFormat.[[Locale]], lfOpts »).
  449. auto* list_format = static_cast<ListFormat*>(MUST(construct(vm, realm.intrinsics().intl_list_format_constructor(), PrimitiveString::create(vm, duration_format.locale()), list_format_options)).ptr());
  450. // FIXME: CreatePartsFromList expects a list of strings and creates a list of Pattern Partition records, but we already created a list of Pattern Partition records
  451. // so we try to hack something together from it that looks mostly right
  452. Vector<String> string_result;
  453. bool merge = false;
  454. for (size_t i = 0; i < result.size(); ++i) {
  455. auto const& part = result[i];
  456. if (part.type == "literal") {
  457. string_result.last() = MUST(String::formatted("{}{}", string_result.last(), part.value));
  458. merge = true;
  459. continue;
  460. }
  461. if (merge) {
  462. string_result.last() = MUST(String::formatted("{}{}", string_result.last(), part.value));
  463. merge = false;
  464. continue;
  465. }
  466. string_result.append(part.value);
  467. }
  468. // 10. Set result to ! CreatePartsFromList(lf, result).
  469. auto final_result = create_parts_from_list(*list_format, string_result);
  470. // 11. Return result.
  471. return final_result;
  472. }
  473. }