Duration.cpp 67 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309
  1. /*
  2. * Copyright (c) 2021, Linus Groh <linusg@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/StringBuilder.h>
  7. #include <LibJS/Runtime/AbstractOperations.h>
  8. #include <LibJS/Runtime/Completion.h>
  9. #include <LibJS/Runtime/GlobalObject.h>
  10. #include <LibJS/Runtime/Object.h>
  11. #include <LibJS/Runtime/Temporal/AbstractOperations.h>
  12. #include <LibJS/Runtime/Temporal/Calendar.h>
  13. #include <LibJS/Runtime/Temporal/Duration.h>
  14. #include <LibJS/Runtime/Temporal/DurationConstructor.h>
  15. #include <LibJS/Runtime/Temporal/Instant.h>
  16. #include <LibJS/Runtime/Temporal/PlainDateTime.h>
  17. #include <LibJS/Runtime/Temporal/TimeZone.h>
  18. #include <LibJS/Runtime/Temporal/ZonedDateTime.h>
  19. namespace JS::Temporal {
  20. // 7 Temporal.Duration Objects, https://tc39.es/proposal-temporal/#sec-temporal-duration-objects
  21. Duration::Duration(double years, double months, double weeks, double days, double hours, double minutes, double seconds, double milliseconds, double microseconds, double nanoseconds, Object& prototype)
  22. : Object(prototype)
  23. , m_years(years)
  24. , m_months(months)
  25. , m_weeks(weeks)
  26. , m_days(days)
  27. , m_hours(hours)
  28. , m_minutes(minutes)
  29. , m_seconds(seconds)
  30. , m_milliseconds(milliseconds)
  31. , m_microseconds(microseconds)
  32. , m_nanoseconds(nanoseconds)
  33. {
  34. }
  35. // 7.5.1 ToTemporalDuration ( item ), https://tc39.es/proposal-temporal/#sec-temporal-totemporalduration
  36. ThrowCompletionOr<Duration*> to_temporal_duration(GlobalObject& global_object, Value item)
  37. {
  38. TemporalDuration result;
  39. // 1. If Type(item) is Object, then
  40. if (item.is_object()) {
  41. // a. If item has an [[InitializedTemporalDuration]] internal slot, then
  42. if (is<Duration>(item.as_object())) {
  43. // i. Return item.
  44. return &static_cast<Duration&>(item.as_object());
  45. }
  46. // b. Let result be ? ToTemporalDurationRecord(item).
  47. result = TRY(to_temporal_duration_record(global_object, item.as_object()));
  48. }
  49. // 2. Else,
  50. else {
  51. // a. Let string be ? ToString(item).
  52. auto string = TRY(item.to_string(global_object));
  53. // b. Let result be ? ParseTemporalDurationString(string).
  54. result = TRY(parse_temporal_duration_string(global_object, string));
  55. }
  56. // 3. Return ? CreateTemporalDuration(result.[[Years]], result.[[Months]], result.[[Weeks]], result.[[Days]], result.[[Hours]], result.[[Minutes]], result.[[Seconds]], result.[[Milliseconds]], result.[[Microseconds]], result.[[Nanoseconds]]).
  57. return create_temporal_duration(global_object, result.years, result.months, result.weeks, result.days, result.hours, result.minutes, result.seconds, result.milliseconds, result.microseconds, result.nanoseconds);
  58. }
  59. // 7.5.2 ToTemporalDurationRecord ( temporalDurationLike ), https://tc39.es/proposal-temporal/#sec-temporal-totemporaldurationrecord
  60. ThrowCompletionOr<TemporalDuration> to_temporal_duration_record(GlobalObject& global_object, Object const& temporal_duration_like)
  61. {
  62. auto& vm = global_object.vm();
  63. // 1. Assert: Type(temporalDurationLike) is Object.
  64. // 2. If temporalDurationLike has an [[InitializedTemporalDuration]] internal slot, then
  65. if (is<Duration>(temporal_duration_like)) {
  66. auto& duration = static_cast<Duration const&>(temporal_duration_like);
  67. // a. Return the Record { [[Years]]: temporalDurationLike.[[Years]], [[Months]]: temporalDurationLike.[[Months]], [[Weeks]]: temporalDurationLike.[[Weeks]], [[Days]]: temporalDurationLike.[[Days]], [[Hours]]: temporalDurationLike.[[Hours]], [[Minutes]]: temporalDurationLike.[[Minutes]], [[Seconds]]: temporalDurationLike.[[Seconds]], [[Milliseconds]]: temporalDurationLike.[[Milliseconds]], [[Microseconds]]: temporalDurationLike.[[Microseconds]], [[Nanoseconds]]: temporalDurationLike.[[Nanoseconds]] }.
  68. return TemporalDuration { .years = duration.years(), .months = duration.months(), .weeks = duration.weeks(), .days = duration.days(), .hours = duration.hours(), .minutes = duration.minutes(), .seconds = duration.seconds(), .milliseconds = duration.milliseconds(), .microseconds = duration.microseconds(), .nanoseconds = duration.nanoseconds() };
  69. }
  70. // 3. Let result be a new Record with all the internal slots given in the Internal Slot column in Table 7.
  71. auto result = TemporalDuration {};
  72. // 4. Let any be false.
  73. auto any = false;
  74. // 5. For each row of Table 7, except the header row, in table order, do
  75. for (auto& [internal_slot, property] : temporal_duration_like_properties<TemporalDuration, double>(vm)) {
  76. // a. Let prop be the Property value of the current row.
  77. // b. Let val be ? Get(temporalDurationLike, prop).
  78. auto value = TRY(temporal_duration_like.get(property));
  79. // c. If val is undefined, then
  80. if (value.is_undefined()) {
  81. // i. Set result's internal slot whose name is the Internal Slot value of the current row to 0.
  82. result.*internal_slot = 0;
  83. }
  84. // d. Else,
  85. else {
  86. // i. Set any to true.
  87. any = true;
  88. // ii. Let val be 𝔽(? ToIntegerWithoutRounding(val)).
  89. value = Value(TRY(to_integer_without_rounding(global_object, value, ErrorType::TemporalInvalidDurationPropertyValueNonIntegral, property.as_string(), value.to_string_without_side_effects())));
  90. // iii. Set result's internal slot whose name is the Internal Slot value of the current row to val.
  91. result.*internal_slot = value.as_double();
  92. }
  93. }
  94. // 6. If any is false, then
  95. if (!any) {
  96. // a. Throw a TypeError exception.
  97. return vm.throw_completion<TypeError>(global_object, ErrorType::TemporalInvalidDurationLikeObject);
  98. }
  99. // 7. Return result.
  100. return result;
  101. }
  102. // 7.5.3 DurationSign ( years, months, weeks, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds ), https://tc39.es/proposal-temporal/#sec-temporal-durationsign
  103. i8 duration_sign(double years, double months, double weeks, double days, double hours, double minutes, double seconds, double milliseconds, double microseconds, double nanoseconds)
  104. {
  105. // 1. For each value v of « years, months, weeks, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds », do
  106. for (auto& v : { years, months, weeks, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds }) {
  107. // a. If v < 0, return −1.
  108. if (v < 0)
  109. return -1;
  110. // b. If v > 0, return 1.
  111. if (v > 0)
  112. return 1;
  113. }
  114. // 2. Return 0.
  115. return 0;
  116. }
  117. // 7.5.4 IsValidDuration ( years, months, weeks, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds ), https://tc39.es/proposal-temporal/#sec-temporal-isvalidduration
  118. bool is_valid_duration(double years, double months, double weeks, double days, double hours, double minutes, double seconds, double milliseconds, double microseconds, double nanoseconds)
  119. {
  120. // 1. Let sign be ! DurationSign(years, months, weeks, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds).
  121. auto sign = duration_sign(years, months, weeks, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds);
  122. // 2. For each value v of « years, months, weeks, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds », do
  123. for (auto& v : { years, months, weeks, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds }) {
  124. // a. If v is not finite, return false.
  125. if (!isfinite(v))
  126. return false;
  127. // b. If v < 0 and sign > 0, return false.
  128. if (v < 0 && sign > 0)
  129. return false;
  130. // c. If v > 0 and sign < 0, return false.
  131. if (v > 0 && sign < 0)
  132. return false;
  133. }
  134. // 3. Return true.
  135. return true;
  136. }
  137. // 7.5.6 ToPartialDuration ( temporalDurationLike ), https://tc39.es/proposal-temporal/#sec-temporal-topartialduration
  138. ThrowCompletionOr<PartialDuration> to_partial_duration(GlobalObject& global_object, Value temporal_duration_like)
  139. {
  140. auto& vm = global_object.vm();
  141. // 1. If Type(temporalDurationLike) is not Object, then
  142. if (!temporal_duration_like.is_object()) {
  143. // a. Throw a TypeError exception.
  144. return vm.throw_completion<TypeError>(global_object, ErrorType::NotAnObject, temporal_duration_like.to_string_without_side_effects());
  145. }
  146. // 2. Let result be the Record { [[Years]]: undefined, [[Months]]: undefined, [[Weeks]]: undefined, [[Days]]: undefined, [[Hours]]: undefined, [[Minutes]]: undefined, [[Seconds]]: undefined, [[Milliseconds]]: undefined, [[Microseconds]]: undefined, [[Nanoseconds]]: undefined }.
  147. auto result = PartialDuration {};
  148. // 3. Let any be false.
  149. auto any = false;
  150. // 4. For each row of Table 7, except the header row, in table order, do
  151. for (auto& [internal_slot, property] : temporal_duration_like_properties<PartialDuration, Optional<double>>(vm)) {
  152. // a. Let property be the Property value of the current row.
  153. // b. Let value be ? Get(temporalDurationLike, property).
  154. auto value = TRY(temporal_duration_like.as_object().get(property));
  155. // c. If value is not undefined, then
  156. if (!value.is_undefined()) {
  157. // i. Set any to true.
  158. any = true;
  159. // ii. Set value to 𝔽(? ToIntegerWithoutRounding(value)).
  160. value = Value(TRY(to_integer_without_rounding(global_object, value, ErrorType::TemporalInvalidDurationPropertyValueNonIntegral, property.as_string(), value.to_string_without_side_effects())));
  161. // iii. Set result's internal slot whose name is the Internal Slot value of the current row to value.
  162. result.*internal_slot = value.as_double();
  163. }
  164. }
  165. // 5. If any is false, then
  166. if (!any) {
  167. // a. Throw a TypeError exception.
  168. return vm.throw_completion<TypeError>(global_object, ErrorType::TemporalInvalidDurationLikeObject);
  169. }
  170. // 6. Return result.
  171. return result;
  172. }
  173. // 7.5.7 CreateTemporalDuration ( years, months, weeks, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds [ , newTarget ] ), https://tc39.es/proposal-temporal/#sec-temporal-createtemporalduration
  174. ThrowCompletionOr<Duration*> create_temporal_duration(GlobalObject& global_object, double years, double months, double weeks, double days, double hours, double minutes, double seconds, double milliseconds, double microseconds, double nanoseconds, FunctionObject const* new_target)
  175. {
  176. auto& vm = global_object.vm();
  177. // 1. If ! IsValidDuration(years, months, weeks, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds) is false, throw a RangeError exception.
  178. if (!is_valid_duration(years, months, weeks, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds))
  179. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidDuration);
  180. // 2. If newTarget is not present, set it to %Temporal.Duration%.
  181. if (!new_target)
  182. new_target = global_object.temporal_duration_constructor();
  183. // 3. Let object be ? OrdinaryCreateFromConstructor(newTarget, "%Temporal.Duration.prototype%", « [[InitializedTemporalDuration]], [[Years]], [[Months]], [[Weeks]], [[Days]], [[Hours]], [[Minutes]], [[Seconds]], [[Milliseconds]], [[Microseconds]], [[Nanoseconds]] »).
  184. // 4. Set object.[[Years]] to years.
  185. // 5. Set object.[[Months]] to months.
  186. // 6. Set object.[[Weeks]] to weeks.
  187. // 7. Set object.[[Days]] to days.
  188. // 8. Set object.[[Hours]] to hours.
  189. // 9. Set object.[[Minutes]] to minutes.
  190. // 10. Set object.[[Seconds]] to seconds.
  191. // 11. Set object.[[Milliseconds]] to milliseconds.
  192. // 12. Set object.[[Microseconds]] to microseconds.
  193. // 13. Set object.[[Nanoseconds]] to nanoseconds.
  194. auto* object = TRY(ordinary_create_from_constructor<Duration>(global_object, *new_target, &GlobalObject::temporal_duration_prototype, years, months, weeks, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds));
  195. // 14. Return object.
  196. return object;
  197. }
  198. // 7.5.8 CreateNegatedTemporalDuration ( duration ), https://tc39.es/proposal-temporal/#sec-temporal-createnegatedtemporalduration
  199. Duration* create_negated_temporal_duration(GlobalObject& global_object, Duration const& duration)
  200. {
  201. // 1. Assert: Type(duration) is Object.
  202. // 2. Assert: duration has an [[InitializedTemporalDuration]] internal slot.
  203. // 3. Return ! CreateTemporalDuration(−duration.[[Years]], −duration.[[Months]], −duration.[[Weeks]], −duration.[[Days]], −duration.[[Hours]], −duration.[[Minutes]], −duration.[[Seconds]], −duration.[[Milliseconds]], −duration.[[Microseconds]], −duration.[[Nanoseconds]]).
  204. return MUST(create_temporal_duration(global_object, -duration.years(), -duration.months(), -duration.weeks(), -duration.days(), -duration.hours(), -duration.minutes(), -duration.seconds(), -duration.milliseconds(), -duration.microseconds(), -duration.nanoseconds()));
  205. }
  206. // 7.5.9 CalculateOffsetShift ( relativeTo, y, mon, w, d, h, min, s, ms, mus, ns ), https://tc39.es/proposal-temporal/#sec-temporal-calculateoffsetshift
  207. ThrowCompletionOr<double> calculate_offset_shift(GlobalObject& global_object, Value relative_to_value, double years, double months, double weeks, double days, double hours, double minutes, double seconds, double milliseconds, double microseconds, double nanoseconds)
  208. {
  209. // 1. If Type(relativeTo) is not Object or relativeTo does not have an [[InitializedTemporalZonedDateTime]] internal slot, return 0.
  210. if (!relative_to_value.is_object() || !is<ZonedDateTime>(relative_to_value.as_object()))
  211. return 0.0;
  212. auto& relative_to = static_cast<ZonedDateTime&>(relative_to_value.as_object());
  213. // 2. Let instant be ! CreateTemporalInstant(relativeTo.[[Nanoseconds]]).
  214. auto* instant = MUST(create_temporal_instant(global_object, relative_to.nanoseconds()));
  215. // 3. Let offsetBefore be ? GetOffsetNanosecondsFor(relativeTo.[[TimeZone]], instant).
  216. auto offset_before = TRY(get_offset_nanoseconds_for(global_object, &relative_to.time_zone(), *instant));
  217. // 4. Let after be ? AddZonedDateTime(relativeTo.[[Nanoseconds]], relativeTo.[[TimeZone]], relativeTo.[[Calendar]], y, mon, w, d, h, min, s, ms, mus, ns).
  218. auto* after = TRY(add_zoned_date_time(global_object, relative_to.nanoseconds(), &relative_to.time_zone(), relative_to.calendar(), years, months, weeks, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds));
  219. // 5. Let instantAfter be ! CreateTemporalInstant(after).
  220. auto* instant_after = MUST(create_temporal_instant(global_object, *after));
  221. // 6. Let offsetAfter be ? GetOffsetNanosecondsFor(relativeTo.[[TimeZone]], instantAfter).
  222. auto offset_after = TRY(get_offset_nanoseconds_for(global_object, &relative_to.time_zone(), *instant_after));
  223. // 7. Return offsetAfter − offsetBefore.
  224. return offset_after - offset_before;
  225. }
  226. // 7.5.10 TotalDurationNanoseconds ( days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds, offsetShift ), https://tc39.es/proposal-temporal/#sec-temporal-totaldurationnanoseconds
  227. BigInt* total_duration_nanoseconds(GlobalObject& global_object, double days, double hours, double minutes, double seconds, double milliseconds, double microseconds, BigInt const& nanoseconds, double offset_shift)
  228. {
  229. auto& vm = global_object.vm();
  230. // 1. Assert: offsetShift is an integer.
  231. VERIFY(offset_shift == trunc(offset_shift));
  232. // 2. Set nanoseconds to ℝ(nanoseconds).
  233. auto result_nanoseconds = nanoseconds.big_integer();
  234. // TODO: Add a way to create SignedBigIntegers from doubles with full precision and remove this restriction
  235. VERIFY(AK::is_within_range<i64>(days) && AK::is_within_range<i64>(hours) && AK::is_within_range<i64>(minutes) && AK::is_within_range<i64>(seconds) && AK::is_within_range<i64>(milliseconds) && AK::is_within_range<i64>(microseconds));
  236. // 3. If days ≠ 0, then
  237. if (days != 0) {
  238. // a. Set nanoseconds to nanoseconds − offsetShift.
  239. result_nanoseconds = result_nanoseconds.minus(Crypto::SignedBigInteger::create_from(offset_shift));
  240. }
  241. // 4. Set hours to ℝ(hours) + ℝ(days) × 24.
  242. auto total_hours = Crypto::SignedBigInteger::create_from(hours).plus(Crypto::SignedBigInteger::create_from(days).multiplied_by(Crypto::UnsignedBigInteger(24)));
  243. // 5. Set minutes to ℝ(minutes) + hours × 60.
  244. auto total_minutes = Crypto::SignedBigInteger::create_from(minutes).plus(total_hours.multiplied_by(Crypto::UnsignedBigInteger(60)));
  245. // 6. Set seconds to ℝ(seconds) + minutes × 60.
  246. auto total_seconds = Crypto::SignedBigInteger::create_from(seconds).plus(total_minutes.multiplied_by(Crypto::UnsignedBigInteger(60)));
  247. // 7. Set milliseconds to ℝ(milliseconds) + seconds × 1000.
  248. auto total_milliseconds = Crypto::SignedBigInteger::create_from(milliseconds).plus(total_seconds.multiplied_by(Crypto::UnsignedBigInteger(1000)));
  249. // 8. Set microseconds to ℝ(microseconds) + milliseconds × 1000.
  250. auto total_microseconds = Crypto::SignedBigInteger::create_from(microseconds).plus(total_milliseconds.multiplied_by(Crypto::UnsignedBigInteger(1000)));
  251. // 9. Return nanoseconds + microseconds × 1000.
  252. return js_bigint(vm, result_nanoseconds.plus(total_microseconds.multiplied_by(Crypto::UnsignedBigInteger(1000))));
  253. }
  254. // 7.5.11 BalanceDuration ( days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds, largestUnit [ , relativeTo ] ), https://tc39.es/proposal-temporal/#sec-temporal-balanceduration
  255. ThrowCompletionOr<BalancedDuration> balance_duration(GlobalObject& global_object, double days, double hours, double minutes, double seconds, double milliseconds, double microseconds, BigInt const& nanoseconds, String const& largest_unit, Object* relative_to)
  256. {
  257. auto& vm = global_object.vm();
  258. // 1. If relativeTo is not present, set relativeTo to undefined.
  259. Crypto::SignedBigInteger total_nanoseconds;
  260. // 2. If Type(relativeTo) is Object and relativeTo has an [[InitializedTemporalZonedDateTime]] internal slot, then
  261. if (relative_to && is<ZonedDateTime>(*relative_to)) {
  262. auto& relative_to_zoned_date_time = static_cast<ZonedDateTime&>(*relative_to);
  263. // a. Let endNs be ? AddZonedDateTime(relativeTo.[[Nanoseconds]], relativeTo.[[TimeZone]], relativeTo.[[Calendar]], 0, 0, 0, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds).
  264. auto* end_ns = TRY(add_zoned_date_time(global_object, relative_to_zoned_date_time.nanoseconds(), &relative_to_zoned_date_time.time_zone(), relative_to_zoned_date_time.calendar(), 0, 0, 0, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds.big_integer().to_double()));
  265. // b. Set nanoseconds to endNs − relativeTo.[[Nanoseconds]].
  266. total_nanoseconds = end_ns->big_integer().minus(relative_to_zoned_date_time.nanoseconds().big_integer());
  267. }
  268. // 3. Else,
  269. else {
  270. // a. Set nanoseconds to ℤ(! TotalDurationNanoseconds(days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds, 0)).
  271. total_nanoseconds = total_duration_nanoseconds(global_object, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds, 0)->big_integer();
  272. }
  273. // 4. If largestUnit is one of "year", "month", "week", or "day", then
  274. if (largest_unit.is_one_of("year"sv, "month"sv, "week"sv, "day"sv)) {
  275. // a. Let result be ? NanosecondsToDays(nanoseconds, relativeTo).
  276. auto result = TRY(nanoseconds_to_days(global_object, *js_bigint(vm, total_nanoseconds), relative_to ?: js_undefined()));
  277. // b. Set days to result.[[Days]].
  278. days = result.days;
  279. // c. Set nanoseconds to result.[[Nanoseconds]].
  280. total_nanoseconds = result.nanoseconds.cell()->big_integer();
  281. }
  282. // 5. Else,
  283. else {
  284. // a. Set days to 0.
  285. days = 0;
  286. }
  287. // 6. Set hours, minutes, seconds, milliseconds, and microseconds to 0.
  288. hours = 0;
  289. minutes = 0;
  290. seconds = 0;
  291. milliseconds = 0;
  292. microseconds = 0;
  293. // 7. Set nanoseconds to ℝ(nanoseconds).
  294. double result_nanoseconds = total_nanoseconds.to_double();
  295. // 8. If nanoseconds < 0, let sign be −1; else, let sign be 1.
  296. i8 sign = total_nanoseconds.is_negative() ? -1 : 1;
  297. // 9. Set nanoseconds to abs(nanoseconds).
  298. total_nanoseconds = Crypto::SignedBigInteger(total_nanoseconds.unsigned_value());
  299. result_nanoseconds = fabs(result_nanoseconds);
  300. // 10. If largestUnit is "year", "month", "week", "day", or "hour", then
  301. if (largest_unit.is_one_of("year"sv, "month"sv, "week"sv, "day"sv, "hour"sv)) {
  302. // a. Set microseconds to floor(nanoseconds / 1000).
  303. auto nanoseconds_division_result = total_nanoseconds.divided_by(Crypto::UnsignedBigInteger(1000));
  304. // b. Set nanoseconds to nanoseconds modulo 1000.
  305. result_nanoseconds = nanoseconds_division_result.remainder.to_double();
  306. // c. Set milliseconds to floor(microseconds / 1000).
  307. auto microseconds_division_result = nanoseconds_division_result.quotient.divided_by(Crypto::UnsignedBigInteger(1000));
  308. // d. Set microseconds to microseconds modulo 1000.
  309. microseconds = microseconds_division_result.remainder.to_double();
  310. // e. Set seconds to floor(milliseconds / 1000).
  311. auto milliseconds_division_result = microseconds_division_result.quotient.divided_by(Crypto::UnsignedBigInteger(1000));
  312. // f. Set milliseconds to milliseconds modulo 1000.
  313. milliseconds = milliseconds_division_result.remainder.to_double();
  314. // g. Set minutes to floor(seconds / 60).
  315. auto seconds_division_result = milliseconds_division_result.quotient.divided_by(Crypto::UnsignedBigInteger(60));
  316. // h. Set seconds to seconds modulo 60.
  317. seconds = seconds_division_result.remainder.to_double();
  318. // i. Set hours to floor(minutes / 60).
  319. auto minutes_division_result = seconds_division_result.quotient.divided_by(Crypto::UnsignedBigInteger(60));
  320. hours = minutes_division_result.quotient.to_double();
  321. // j. Set minutes to minutes modulo 60.
  322. minutes = minutes_division_result.remainder.to_double();
  323. }
  324. // 11. Else if largestUnit is "minute", then
  325. else if (largest_unit == "minute"sv) {
  326. // a. Set microseconds to floor(nanoseconds / 1000).
  327. auto nanoseconds_division_result = total_nanoseconds.divided_by(Crypto::UnsignedBigInteger(1000));
  328. // b. Set nanoseconds to nanoseconds modulo 1000.
  329. result_nanoseconds = nanoseconds_division_result.remainder.to_double();
  330. // c. Set milliseconds to floor(microseconds / 1000).
  331. auto microseconds_division_result = nanoseconds_division_result.quotient.divided_by(Crypto::UnsignedBigInteger(1000));
  332. // d. Set microseconds to microseconds modulo 1000.
  333. microseconds = microseconds_division_result.remainder.to_double();
  334. // e. Set seconds to floor(milliseconds / 1000).
  335. auto milliseconds_division_result = microseconds_division_result.quotient.divided_by(Crypto::UnsignedBigInteger(1000));
  336. // f. Set milliseconds to milliseconds modulo 1000.
  337. milliseconds = milliseconds_division_result.remainder.to_double();
  338. // g. Set minutes to floor(seconds / 60).
  339. auto seconds_division_result = milliseconds_division_result.quotient.divided_by(Crypto::UnsignedBigInteger(60));
  340. minutes = seconds_division_result.quotient.to_double();
  341. // h. Set seconds to seconds modulo 60.
  342. seconds = seconds_division_result.remainder.to_double();
  343. }
  344. // 12. Else if largestUnit is "second", then
  345. else if (largest_unit == "second"sv) {
  346. // a. Set microseconds to floor(nanoseconds / 1000).
  347. auto nanoseconds_division_result = total_nanoseconds.divided_by(Crypto::UnsignedBigInteger(1000));
  348. // b. Set nanoseconds to nanoseconds modulo 1000.
  349. result_nanoseconds = nanoseconds_division_result.remainder.to_double();
  350. // c. Set milliseconds to floor(microseconds / 1000).
  351. auto microseconds_division_result = nanoseconds_division_result.quotient.divided_by(Crypto::UnsignedBigInteger(1000));
  352. // d. Set microseconds to microseconds modulo 1000.
  353. microseconds = microseconds_division_result.remainder.to_double();
  354. // e. Set seconds to floor(milliseconds / 1000).
  355. auto milliseconds_division_result = microseconds_division_result.quotient.divided_by(Crypto::UnsignedBigInteger(1000));
  356. seconds = milliseconds_division_result.quotient.to_double();
  357. // f. Set milliseconds to milliseconds modulo 1000.
  358. milliseconds = milliseconds_division_result.remainder.to_double();
  359. }
  360. // 13. Else if largestUnit is "millisecond", then
  361. else if (largest_unit == "millisecond"sv) {
  362. // a. Set microseconds to floor(nanoseconds / 1000).
  363. auto nanoseconds_division_result = total_nanoseconds.divided_by(Crypto::UnsignedBigInteger(1000));
  364. // b. Set nanoseconds to nanoseconds modulo 1000.
  365. result_nanoseconds = nanoseconds_division_result.remainder.to_double();
  366. // c. Set milliseconds to floor(microseconds / 1000).
  367. auto microseconds_division_result = nanoseconds_division_result.quotient.divided_by(Crypto::UnsignedBigInteger(1000));
  368. milliseconds = microseconds_division_result.quotient.to_double();
  369. // d. Set microseconds to microseconds modulo 1000.
  370. microseconds = microseconds_division_result.remainder.to_double();
  371. }
  372. // 14. Else if largestUnit is "microsecond", then
  373. else if (largest_unit == "microsecond"sv) {
  374. // a. Set microseconds to floor(nanoseconds / 1000).
  375. auto nanoseconds_division_result = total_nanoseconds.divided_by(Crypto::UnsignedBigInteger(1000));
  376. microseconds = nanoseconds_division_result.quotient.to_double();
  377. // b. Set nanoseconds to nanoseconds modulo 1000.
  378. result_nanoseconds = nanoseconds_division_result.remainder.to_double();
  379. }
  380. // 15. Else,
  381. else {
  382. // a. Assert: largestUnit is "nanosecond".
  383. VERIFY(largest_unit == "nanosecond"sv);
  384. }
  385. // 16. Return the Record { [[Days]]: 𝔽(days), [[Hours]]: 𝔽(hours × sign), [[Minutes]]: 𝔽(minutes × sign), [[Seconds]]: 𝔽(seconds × sign), [[Milliseconds]]: 𝔽(milliseconds × sign), [[Microseconds]]: 𝔽(microseconds × sign), [[Nanoseconds]]: 𝔽(nanoseconds × sign) }.
  386. return BalancedDuration { .days = days, .hours = hours * sign, .minutes = minutes * sign, .seconds = seconds * sign, .milliseconds = milliseconds * sign, .microseconds = microseconds * sign, .nanoseconds = result_nanoseconds * sign };
  387. }
  388. // 7.5.12 UnbalanceDurationRelative ( years, months, weeks, days, largestUnit, relativeTo ), https://tc39.es/proposal-temporal/#sec-temporal-unbalancedurationrelative
  389. ThrowCompletionOr<UnbalancedDuration> unbalance_duration_relative(GlobalObject& global_object, double years, double months, double weeks, double days, String const& largest_unit, Value relative_to)
  390. {
  391. auto& vm = global_object.vm();
  392. // 1. If largestUnit is "year", or years, months, weeks, and days are all 0, then
  393. if (largest_unit == "year"sv || (years == 0 && months == 0 && weeks == 0 && days == 0)) {
  394. // a. Return the Record { [[Years]]: years, [[Months]]: months, [[Weeks]]: weeks, [[Days]]: days }.
  395. return UnbalancedDuration { .years = years, .months = months, .weeks = weeks, .days = days };
  396. }
  397. // 2. Let sign be ! DurationSign(years, months, weeks, days, 0, 0, 0, 0, 0, 0).
  398. auto sign = duration_sign(years, months, weeks, days, 0, 0, 0, 0, 0, 0);
  399. // 3. Assert: sign ≠ 0.
  400. VERIFY(sign != 0);
  401. // 4. Let oneYear be ! CreateTemporalDuration(sign, 0, 0, 0, 0, 0, 0, 0, 0, 0).
  402. auto* one_year = MUST(create_temporal_duration(global_object, sign, 0, 0, 0, 0, 0, 0, 0, 0, 0));
  403. // 5. Let oneMonth be ! CreateTemporalDuration(0, sign, 0, 0, 0, 0, 0, 0, 0, 0).
  404. auto* one_month = MUST(create_temporal_duration(global_object, 0, sign, 0, 0, 0, 0, 0, 0, 0, 0));
  405. // 6. Let oneWeek be ! CreateTemporalDuration(0, 0, sign, 0, 0, 0, 0, 0, 0, 0).
  406. auto* one_week = MUST(create_temporal_duration(global_object, 0, 0, sign, 0, 0, 0, 0, 0, 0, 0));
  407. Object* calendar;
  408. // 7. If relativeTo is not undefined, then
  409. if (!relative_to.is_undefined()) {
  410. // a. Set relativeTo to ? ToTemporalDate(relativeTo).
  411. auto* relative_to_plain_date = TRY(to_temporal_date(global_object, relative_to));
  412. relative_to = relative_to_plain_date;
  413. // b. Let calendar be relativeTo.[[Calendar]].
  414. calendar = &relative_to_plain_date->calendar();
  415. }
  416. // 8. Else,
  417. else {
  418. // a. Let calendar be undefined.
  419. calendar = nullptr;
  420. }
  421. // 9. If largestUnit is "month", then
  422. if (largest_unit == "month"sv) {
  423. // a. If calendar is undefined, then
  424. if (!calendar) {
  425. // i. Throw a RangeError exception.
  426. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalMissingStartingPoint, "months");
  427. }
  428. // b. Let dateAdd be ? GetMethod(calendar, "dateAdd").
  429. auto* date_add = TRY(Value(calendar).get_method(global_object, vm.names.dateAdd));
  430. // c. Let dateUntil be ? GetMethod(calendar, "dateUntil").
  431. auto* date_until = TRY(Value(calendar).get_method(global_object, vm.names.dateUntil));
  432. // d. Repeat, while years ≠ 0,
  433. while (years != 0) {
  434. // i. Let addOptions be ! OrdinaryObjectCreate(null).
  435. auto* add_options = Object::create(global_object, nullptr);
  436. // ii. Let newRelativeTo be ? CalendarDateAdd(calendar, relativeTo, oneYear, addOptions, dateAdd).
  437. auto* new_relative_to = TRY(calendar_date_add(global_object, *calendar, relative_to, *one_year, add_options, date_add));
  438. // iii. Let untilOptions be ! OrdinaryObjectCreate(null).
  439. auto* until_options = Object::create(global_object, nullptr);
  440. // iv. Perform ! CreateDataPropertyOrThrow(untilOptions, "largestUnit", "month").
  441. MUST(until_options->create_data_property_or_throw(vm.names.largestUnit, js_string(vm, "month"sv)));
  442. // v. Let untilResult be ? CalendarDateUntil(calendar, relativeTo, newRelativeTo, untilOptions, dateUntil).
  443. auto* until_result = TRY(calendar_date_until(global_object, *calendar, relative_to, new_relative_to, *until_options, date_until));
  444. // vi. Let oneYearMonths be untilResult.[[Months]].
  445. auto one_year_months = until_result->months();
  446. // vii. Set relativeTo to newRelativeTo.
  447. relative_to = new_relative_to;
  448. // viii. Set years to years − sign.
  449. years -= sign;
  450. // ix. Set months to months + oneYearMonths.
  451. months += one_year_months;
  452. }
  453. }
  454. // 10. Else if largestUnit is "week", then
  455. else if (largest_unit == "week"sv) {
  456. // a. If calendar is undefined, then
  457. if (!calendar) {
  458. // i. Throw a RangeError exception.
  459. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalMissingStartingPoint, "weeks");
  460. }
  461. // b. Repeat, while years ≠ 0,
  462. while (years != 0) {
  463. // i. Let moveResult be ? MoveRelativeDate(calendar, relativeTo, oneYear).
  464. auto move_result = TRY(move_relative_date(global_object, *calendar, verify_cast<PlainDate>(relative_to.as_object()), *one_year));
  465. // ii. Set relativeTo to moveResult.[[RelativeTo]].
  466. relative_to = move_result.relative_to.cell();
  467. // iii. Set days to days + moveResult.[[Days]].
  468. days += move_result.days;
  469. // iv. Set years to years − sign.
  470. years -= sign;
  471. }
  472. // c. Repeat, while months ≠ 0,
  473. while (months != 0) {
  474. // i. Let moveResult be ? MoveRelativeDate(calendar, relativeTo, oneMonth).
  475. auto move_result = TRY(move_relative_date(global_object, *calendar, verify_cast<PlainDate>(relative_to.as_object()), *one_month));
  476. // ii. Set relativeTo to moveResult.[[RelativeTo]].
  477. relative_to = move_result.relative_to.cell();
  478. // iii. Set days to days + moveResult.[[Days]].
  479. days += move_result.days;
  480. // iv. Set months to months − sign.
  481. months -= sign;
  482. }
  483. }
  484. // 11. Else,
  485. else {
  486. // a. If any of years, months, and weeks are not zero, then
  487. if (years != 0 || months != 0 || weeks != 0) {
  488. // i. If calendar is undefined, then
  489. if (!calendar) {
  490. // i. Throw a RangeError exception.
  491. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalMissingStartingPoint, "calendar units");
  492. }
  493. // ii. Repeat, while years ≠ 0,
  494. while (years != 0) {
  495. // 1. Let moveResult be ? MoveRelativeDate(calendar, relativeTo, oneYear).
  496. auto move_result = TRY(move_relative_date(global_object, *calendar, verify_cast<PlainDate>(relative_to.as_object()), *one_year));
  497. // 2. Set relativeTo to moveResult.[[RelativeTo]].
  498. relative_to = move_result.relative_to.cell();
  499. // 3. Set days to days + moveResult.[[Days]].
  500. days += move_result.days;
  501. // 4. Set years to years − sign.
  502. years -= sign;
  503. }
  504. // iii. Repeat, while months ≠ 0,
  505. while (months != 0) {
  506. // 1. Let moveResult be ? MoveRelativeDate(calendar, relativeTo, oneMonth).
  507. auto move_result = TRY(move_relative_date(global_object, *calendar, verify_cast<PlainDate>(relative_to.as_object()), *one_month));
  508. // 2. Set relativeTo to moveResult.[[RelativeTo]].
  509. relative_to = move_result.relative_to.cell();
  510. // 3. Set days to days +moveResult.[[Days]].
  511. days += move_result.days;
  512. // 4. Set months to months − sign.
  513. months -= sign;
  514. }
  515. // iv. Repeat, while weeks ≠ 0,
  516. while (weeks != 0) {
  517. // 1. Let moveResult be ? MoveRelativeDate(calendar, relativeTo, oneWeek).
  518. auto move_result = TRY(move_relative_date(global_object, *calendar, verify_cast<PlainDate>(relative_to.as_object()), *one_week));
  519. // 2. Set relativeTo to moveResult.[[RelativeTo]].
  520. relative_to = move_result.relative_to.cell();
  521. // 3. Set days to days + moveResult.[[Days]].
  522. days += move_result.days;
  523. // 4. Set weeks to weeks − sign.
  524. weeks -= sign;
  525. }
  526. }
  527. }
  528. // 12. Return the Record { [[Years]]: years, [[Months]]: months, [[Weeks]]: weeks, [[Days]]: days }.
  529. return UnbalancedDuration { .years = years, .months = months, .weeks = weeks, .days = days };
  530. }
  531. // 7.5.16 MoveRelativeDate ( calendar, relativeTo, duration ), https://tc39.es/proposal-temporal/#sec-temporal-moverelativedate
  532. ThrowCompletionOr<MoveRelativeDateResult> move_relative_date(GlobalObject& global_object, Object& calendar, PlainDate& relative_to, Duration& duration)
  533. {
  534. // 1. Assert: Type(relativeTo) is Object.
  535. // 2. Assert: relativeTo has an [[InitializedTemporalDate]] internal slot.
  536. // 3. Let options be ! OrdinaryObjectCreate(null).
  537. auto* options = Object::create(global_object, nullptr);
  538. // 4. Let newDate be ? CalendarDateAdd(calendar, relativeTo, duration, options).
  539. auto* new_date = TRY(calendar_date_add(global_object, calendar, &relative_to, duration, options));
  540. // 5. Let days be ! DaysUntil(relativeTo, newDate).
  541. auto days = days_until(global_object, relative_to, *new_date);
  542. // 6. Return the Record { [[RelativeTo]]: newDate, [[Days]]: days }.
  543. return MoveRelativeDateResult { .relative_to = make_handle(new_date), .days = days };
  544. }
  545. // 7.5.17 MoveRelativeZonedDateTime ( zonedDateTime, years, months, weeks, days ), https://tc39.es/proposal-temporal/#sec-temporal-moverelativezoneddatetime
  546. ThrowCompletionOr<ZonedDateTime*> move_relative_zoned_date_time(GlobalObject& global_object, ZonedDateTime& zoned_date_time, double years, double months, double weeks, double days)
  547. {
  548. // 1. Let intermediateNs be ? AddZonedDateTime(zonedDateTime.[[Nanoseconds]], zonedDateTime.[[TimeZone]], zonedDateTime.[[Calendar]], years, months, weeks, days, 0, 0, 0, 0, 0, 0).
  549. auto* intermediate_ns = TRY(add_zoned_date_time(global_object, zoned_date_time.nanoseconds(), &zoned_date_time.time_zone(), zoned_date_time.calendar(), years, months, weeks, days, 0, 0, 0, 0, 0, 0));
  550. // 2. Return ! CreateTemporalZonedDateTime(intermediateNs, zonedDateTime.[[TimeZone]], zonedDateTime.[[Calendar]]).
  551. return MUST(create_temporal_zoned_date_time(global_object, *intermediate_ns, zoned_date_time.time_zone(), zoned_date_time.calendar()));
  552. }
  553. // 7.5.18 RoundDuration ( years, months, weeks, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds, increment, unit, roundingMode [ , relativeTo ] ), https://tc39.es/proposal-temporal/#sec-temporal-roundduration
  554. ThrowCompletionOr<RoundedDuration> round_duration(GlobalObject& global_object, double years, double months, double weeks, double days, double hours, double minutes, double seconds, double milliseconds, double microseconds, double nanoseconds, u32 increment, StringView unit, StringView rounding_mode, Object* relative_to_object)
  555. {
  556. auto& vm = global_object.vm();
  557. Object* calendar = nullptr;
  558. double fractional_seconds = 0;
  559. // 1. If relativeTo is not present, set relativeTo to undefined.
  560. // NOTE: `relative_to_object` and `relative_to` in the various code paths below are all the same as far as the
  561. // spec is concerned, but the latter is more strictly typed for convenience.
  562. PlainDate* relative_to = nullptr;
  563. // 2. Let years, months, weeks, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds, and increment each be the mathematical values of themselves.
  564. // FIXME: assuming "smallestUnit" as the option name here leads to confusing error messages in some cases:
  565. // > new Temporal.Duration().total({ unit: "month" })
  566. // Uncaught exception: [RangeError] month is not a valid value for option smallestUnit
  567. // 3. If unit is "year", "month", or "week", and relativeTo is undefined, then
  568. if (unit.is_one_of("year"sv, "month"sv, "week"sv) && !relative_to_object) {
  569. // a. Throw a RangeError exception.
  570. return vm.throw_completion<RangeError>(global_object, ErrorType::OptionIsNotValidValue, unit, "smallestUnit"sv);
  571. }
  572. // 4. Let zonedRelativeTo be undefined.
  573. ZonedDateTime* zoned_relative_to = nullptr;
  574. // 5. If relativeTo is not undefined, then
  575. if (relative_to_object) {
  576. // a. If relativeTo has an [[InitializedTemporalZonedDateTime]] internal slot, then
  577. if (is<ZonedDateTime>(relative_to_object)) {
  578. auto* relative_to_zoned_date_time = static_cast<ZonedDateTime*>(relative_to_object);
  579. // i. Let instant be ! CreateTemporalInstant(relativeTo.[[Nanoseconds]]).
  580. auto* instant = MUST(create_temporal_instant(global_object, relative_to_zoned_date_time->nanoseconds()));
  581. // ii. Set zonedRelativeTo to relativeTo.
  582. zoned_relative_to = relative_to_zoned_date_time;
  583. // iii. Let plainDateTime be ? BuiltinTimeZoneGetPlainDateTimeFor(relativeTo.[[TimeZone]], instant, relativeTo.[[Calendar]]).
  584. auto* plain_date_time = TRY(builtin_time_zone_get_plain_date_time_for(global_object, &relative_to_zoned_date_time->time_zone(), *instant, relative_to_zoned_date_time->calendar()));
  585. // iv. Set relativeTo to ! CreateTemporalDate(plainDateTime.[[ISOYear]], plainDateTime.[[ISOMonth]], plainDateTime.[[ISODay]], relativeTo.[[Calendar]]).
  586. relative_to = TRY(create_temporal_date(global_object, plain_date_time->iso_year(), plain_date_time->iso_month(), plain_date_time->iso_day(), relative_to_zoned_date_time->calendar()));
  587. }
  588. // b. Else,
  589. else {
  590. // i. Assert: relativeTo has an [[InitializedTemporalDate]] internal slot.
  591. VERIFY(is<PlainDate>(relative_to_object));
  592. relative_to = static_cast<PlainDate*>(relative_to_object);
  593. }
  594. // c. Let calendar be relativeTo.[[Calendar]].
  595. calendar = &relative_to->calendar();
  596. }
  597. // 6. If unit is one of "year", "month", "week", or "day", then
  598. if (unit.is_one_of("year"sv, "month"sv, "week"sv, "day"sv)) {
  599. auto* nanoseconds_bigint = js_bigint(vm, Crypto::SignedBigInteger::create_from((i64)nanoseconds));
  600. // a. Let nanoseconds be ! TotalDurationNanoseconds(0, hours, minutes, seconds, milliseconds, microseconds, nanoseconds, 0).
  601. nanoseconds_bigint = total_duration_nanoseconds(global_object, 0, hours, minutes, seconds, milliseconds, microseconds, *nanoseconds_bigint, 0);
  602. // b. Let intermediate be undefined.
  603. ZonedDateTime* intermediate = nullptr;
  604. // c. If zonedRelativeTo is not undefined, then
  605. if (zoned_relative_to) {
  606. // i. Let intermediate be ? MoveRelativeZonedDateTime(zonedRelativeTo, years, months, weeks, days).
  607. intermediate = TRY(move_relative_zoned_date_time(global_object, *zoned_relative_to, years, months, weeks, days));
  608. }
  609. // d. Let result be ? NanosecondsToDays(nanoseconds, intermediate).
  610. auto result = TRY(nanoseconds_to_days(global_object, *nanoseconds_bigint, intermediate));
  611. // e. Set days to days + result.[[Days]] + result.[[Nanoseconds]] / result.[[DayLength]].
  612. auto nanoseconds_division_result = result.nanoseconds.cell()->big_integer().divided_by(Crypto::UnsignedBigInteger::create_from((u64)result.day_length));
  613. days += result.days + nanoseconds_division_result.quotient.to_double() + nanoseconds_division_result.remainder.to_double() / result.day_length;
  614. // f. Set hours, minutes, seconds, milliseconds, microseconds, and nanoseconds to 0.
  615. hours = 0;
  616. minutes = 0;
  617. seconds = 0;
  618. milliseconds = 0;
  619. microseconds = 0;
  620. nanoseconds = 0;
  621. }
  622. // 7. Else,
  623. else {
  624. // a. Let fractionalSeconds be nanoseconds × 10^−9 + microseconds × 10^−6 + milliseconds × 10^−3 + seconds.
  625. fractional_seconds = nanoseconds * 0.000000001 + microseconds * 0.000001 + milliseconds * 0.001 + seconds;
  626. }
  627. // 8. Let remainder be undefined.
  628. double remainder = 0;
  629. // 9. If unit is "year", then
  630. if (unit == "year"sv) {
  631. VERIFY(relative_to);
  632. // a. Let yearsDuration be ? CreateTemporalDuration(years, 0, 0, 0, 0, 0, 0, 0, 0, 0).
  633. auto* years_duration = TRY(create_temporal_duration(global_object, years, 0, 0, 0, 0, 0, 0, 0, 0, 0));
  634. // b. Let dateAdd be ? GetMethod(calendar, "dateAdd").
  635. auto* date_add = TRY(Value(calendar).get_method(global_object, vm.names.dateAdd));
  636. // c. Let firstAddOptions be ! OrdinaryObjectCreate(null).
  637. auto* first_add_options = Object::create(global_object, nullptr);
  638. // d. Let yearsLater be ? CalendarDateAdd(calendar, relativeTo, yearsDuration, firstAddOptions, dateAdd).
  639. auto* years_later = TRY(calendar_date_add(global_object, *calendar, relative_to, *years_duration, first_add_options, date_add));
  640. // e. Let yearsMonthsWeeks be ? CreateTemporalDuration(years, months, weeks, 0, 0, 0, 0, 0, 0, 0).
  641. auto* years_months_weeks = TRY(create_temporal_duration(global_object, years, months, weeks, 0, 0, 0, 0, 0, 0, 0));
  642. // f. Let secondAddOptions be ! OrdinaryObjectCreate(null).
  643. auto* second_add_options = Object::create(global_object, nullptr);
  644. // g. Let yearsMonthsWeeksLater be ? CalendarDateAdd(calendar, relativeTo, yearsMonthsWeeks, secondAddOptions, dateAdd).
  645. auto* years_months_weeks_later = TRY(calendar_date_add(global_object, *calendar, relative_to, *years_months_weeks, second_add_options, date_add));
  646. // h. Let monthsWeeksInDays be ? DaysUntil(yearsLater, yearsMonthsWeeksLater).
  647. auto months_weeks_in_days = days_until(global_object, *years_later, *years_months_weeks_later);
  648. // i. Set relativeTo to yearsLater.
  649. relative_to = years_later;
  650. // j. Let days be days + monthsWeeksInDays.
  651. days += months_weeks_in_days;
  652. // k. Let daysDuration be ? CreateTemporalDuration(0, 0, 0, days, 0, 0, 0, 0, 0, 0).
  653. auto* days_duration = TRY(create_temporal_duration(global_object, 0, 0, 0, days, 0, 0, 0, 0, 0, 0));
  654. // l. Let thirdAddOptions be ! OrdinaryObjectCreate(null).
  655. auto* third_add_options = Object::create(global_object, nullptr);
  656. // m. Let daysLater be ? CalendarDateAdd(calendar, relativeTo, daysDuration, thirdAddOptions, dateAdd).
  657. auto* days_later = TRY(calendar_date_add(global_object, *calendar, relative_to, *days_duration, third_add_options, date_add));
  658. // n. Let untilOptions be ! OrdinaryObjectCreate(null).
  659. auto* until_options = Object::create(global_object, nullptr);
  660. // o. Perform ! CreateDataPropertyOrThrow(untilOptions, "largestUnit", "year").
  661. MUST(until_options->create_data_property_or_throw(vm.names.largestUnit, js_string(vm, "year"sv)));
  662. // p. Let timePassed be ? CalendarDateUntil(calendar, relativeTo, daysLater, untilOptions).
  663. auto* time_passed = TRY(calendar_date_until(global_object, *calendar, relative_to, days_later, *until_options));
  664. // q. Let yearsPassed be timePassed.[[Years]].
  665. auto years_passed = time_passed->years();
  666. // r. Set years to years + yearsPassed.
  667. years += years_passed;
  668. // s. Let oldRelativeTo be relativeTo.
  669. auto* old_relative_to = relative_to;
  670. // t. Let yearsDuration be ? CreateTemporalDuration(yearsPassed, 0, 0, 0, 0, 0, 0, 0, 0, 0).
  671. years_duration = TRY(create_temporal_duration(global_object, years_passed, 0, 0, 0, 0, 0, 0, 0, 0, 0));
  672. // u. Let fourthAddOptions be ! OrdinaryObjectCreate(null).
  673. auto* fourth_add_options = Object::create(global_object, nullptr);
  674. // v. Set relativeTo to ? CalendarDateAdd(calendar, relativeTo, yearsDuration, fourthAddOptions, dateAdd).
  675. relative_to = TRY(calendar_date_add(global_object, *calendar, relative_to, *years_duration, fourth_add_options, date_add));
  676. // w. Let daysPassed be ? DaysUntil(oldRelativeTo, relativeTo).
  677. auto days_passed = days_until(global_object, *old_relative_to, *relative_to);
  678. // x. Set days to days - daysPassed.
  679. days -= days_passed;
  680. // y. Let sign be ! Sign(days).
  681. auto sign = JS::Temporal::sign(days);
  682. // z. If sign is 0, set sign to 1.
  683. if (sign == 0)
  684. sign = 1;
  685. // aa. Let oneYear be ? CreateTemporalDuration(sign, 0, 0, 0, 0, 0, 0, 0, 0, 0).
  686. auto* one_year = TRY(create_temporal_duration(global_object, sign, 0, 0, 0, 0, 0, 0, 0, 0, 0));
  687. // ab. Let moveResult be ? MoveRelativeDate(calendar, relativeTo, oneYear).
  688. auto move_result = TRY(move_relative_date(global_object, *calendar, *relative_to, *one_year));
  689. // ac. Let oneYearDays be moveResult.[[Days]].
  690. auto one_year_days = move_result.days;
  691. // ad. Let fractionalYears be years + days / abs(oneYearDays).
  692. auto fractional_years = years + days / fabs(one_year_days);
  693. // ae. Set years to ! RoundNumberToIncrement(fractionalYears, increment, roundingMode).
  694. years = (double)round_number_to_increment(fractional_years, increment, rounding_mode);
  695. // af. Set remainder to fractionalYears - years.
  696. remainder = fractional_years - years;
  697. // ag. Set months, weeks, and days to 0.
  698. months = 0;
  699. weeks = 0;
  700. days = 0;
  701. }
  702. // 10. Else if unit is "month", then
  703. else if (unit == "month"sv) {
  704. VERIFY(relative_to);
  705. // a. Let yearsMonths be ? CreateTemporalDuration(years, months, 0, 0, 0, 0, 0, 0, 0, 0).
  706. auto* years_months = TRY(create_temporal_duration(global_object, years, months, 0, 0, 0, 0, 0, 0, 0, 0));
  707. // b. Let dateAdd be ? GetMethod(calendar, "dateAdd").
  708. auto* date_add = TRY(Value(calendar).get_method(global_object, vm.names.dateAdd));
  709. // c. Let firstAddOptions be ! OrdinaryObjectCreate(null).
  710. auto* first_add_options = Object::create(global_object, nullptr);
  711. // d. Let yearsMonthsLater be ? CalendarDateAdd(calendar, relativeTo, yearsMonths, firstAddOptions, dateAdd).
  712. auto* years_months_later = TRY(calendar_date_add(global_object, *calendar, relative_to, *years_months, first_add_options, date_add));
  713. // e. Let yearsMonthsWeeks be ? CreateTemporalDuration(years, months, weeks, 0, 0, 0, 0, 0, 0, 0).
  714. auto* years_months_weeks = TRY(create_temporal_duration(global_object, years, months, weeks, 0, 0, 0, 0, 0, 0, 0));
  715. // f. Let secondAddOptions be ! OrdinaryObjectCreate(null).
  716. auto* seconds_add_options = Object::create(global_object, nullptr);
  717. // g. Let yearsMonthsWeeksLater be ? CalendarDateAdd(calendar, relativeTo, yearsMonthsWeeks, secondAddOptions, dateAdd).
  718. auto* years_months_weeks_later = TRY(calendar_date_add(global_object, *calendar, relative_to, *years_months_weeks, seconds_add_options, date_add));
  719. // h. Let weeksInDays be ? DaysUntil(yearsMonthsLater, yearsMonthsWeeksLater).
  720. auto weeks_in_days = days_until(global_object, *years_months_later, *years_months_weeks_later);
  721. // i. Set relativeTo to yearsMonthsLater.
  722. relative_to = years_months_later;
  723. // j. Let days be days + weeksInDays.
  724. days += weeks_in_days;
  725. // k. Let sign be ! Sign(days).
  726. auto sign = JS::Temporal::sign(days);
  727. // l. If sign is 0, set sign to 1.
  728. if (sign == 0)
  729. sign = 1;
  730. // m. Let oneMonth be ? CreateTemporalDuration(0, sign, 0, 0, 0, 0, 0, 0, 0, 0).
  731. auto* one_month = TRY(create_temporal_duration(global_object, 0, sign, 0, 0, 0, 0, 0, 0, 0, 0));
  732. // n. Let moveResult be ? MoveRelativeDate(calendar, relativeTo, oneMonth).
  733. auto move_result = TRY(move_relative_date(global_object, *calendar, *relative_to, *one_month));
  734. // o. Set relativeTo to moveResult.[[RelativeTo]].
  735. relative_to = move_result.relative_to.cell();
  736. // p. Let oneMonthDays be moveResult.[[Days]].
  737. auto one_month_days = move_result.days;
  738. // q. Repeat, while abs(days) ≥ abs(oneMonthDays),
  739. while (fabs(days) >= fabs(one_month_days)) {
  740. // i. Set months to months + sign.
  741. months += sign;
  742. // ii. Set days to days − oneMonthDays.
  743. days -= one_month_days;
  744. // iii. Set moveResult to ? MoveRelativeDate(calendar, relativeTo, oneMonth).
  745. move_result = TRY(move_relative_date(global_object, *calendar, *relative_to, *one_month));
  746. // iv. Set relativeTo to moveResult.[[RelativeTo]].
  747. relative_to = move_result.relative_to.cell();
  748. // v. Set oneMonthDays to moveResult.[[Days]].
  749. one_month_days = move_result.days;
  750. }
  751. // r. Let fractionalMonths be months + days / abs(oneMonthDays).
  752. auto fractional_months = months + days / fabs(one_month_days);
  753. // s. Set months to ! RoundNumberToIncrement(fractionalMonths, increment, roundingMode).
  754. months = (double)round_number_to_increment(fractional_months, increment, rounding_mode);
  755. // t. Set remainder to fractionalMonths - months.
  756. remainder = fractional_months - months;
  757. // u. Set weeks and days to 0.
  758. weeks = 0;
  759. days = 0;
  760. }
  761. // 11. Else if unit is "week", then
  762. else if (unit == "week"sv) {
  763. VERIFY(relative_to);
  764. // a. Let sign be ! Sign(days).
  765. auto sign = JS::Temporal::sign(days);
  766. // b. If sign is 0, set sign to 1.
  767. if (sign == 0)
  768. sign = 1;
  769. // c. Let oneWeek be ? CreateTemporalDuration(0, 0, sign, 0, 0, 0, 0, 0, 0, 0).
  770. auto* one_week = TRY(create_temporal_duration(global_object, 0, 0, sign, 0, 0, 0, 0, 0, 0, 0));
  771. // d. Let moveResult be ? MoveRelativeDate(calendar, relativeTo, oneWeek).
  772. auto move_result = TRY(move_relative_date(global_object, *calendar, *relative_to, *one_week));
  773. // e. Set relativeTo to moveResult.[[RelativeTo]].
  774. relative_to = move_result.relative_to.cell();
  775. // f. Let oneWeekDays be moveResult.[[Days]].
  776. auto one_week_days = move_result.days;
  777. // g. Repeat, while abs(days) ≥ abs(oneWeekDays),
  778. while (fabs(days) >= fabs(one_week_days)) {
  779. // i. Set weeks to weeks + sign.
  780. weeks += sign;
  781. // ii. Set days to days − oneWeekDays.
  782. days -= one_week_days;
  783. // iii. Set moveResult to ? MoveRelativeDate(calendar, relativeTo, oneWeek).
  784. move_result = TRY(move_relative_date(global_object, *calendar, *relative_to, *one_week));
  785. // iv. Set relativeTo to moveResult.[[RelativeTo]].
  786. relative_to = move_result.relative_to.cell();
  787. // v. Set oneWeekDays to moveResult.[[Days]].
  788. one_week_days = move_result.days;
  789. }
  790. // h. Let fractionalWeeks be weeks + days / abs(oneWeekDays).
  791. auto fractional_weeks = weeks + days / fabs(one_week_days);
  792. // i. Set weeks to ! RoundNumberToIncrement(fractionalWeeks, increment, roundingMode).
  793. weeks = (double)round_number_to_increment(fractional_weeks, increment, rounding_mode);
  794. // j. Set remainder to fractionalWeeks - weeks.
  795. remainder = fractional_weeks - weeks;
  796. // k. Set days to 0.
  797. days = 0;
  798. }
  799. // 12. Else if unit is "day", then
  800. else if (unit == "day"sv) {
  801. // a. Let fractionalDays be days.
  802. auto fractional_days = days;
  803. // b. Set days to ! RoundNumberToIncrement(days, increment, roundingMode).
  804. days = (double)round_number_to_increment(days, increment, rounding_mode);
  805. // c. Set remainder to fractionalDays - days.
  806. remainder = fractional_days - days;
  807. }
  808. // 13. Else if unit is "hour", then
  809. else if (unit == "hour"sv) {
  810. // a. Let fractionalHours be (fractionalSeconds / 60 + minutes) / 60 + hours.
  811. auto fractional_hours = (fractional_seconds / 60 + minutes) / 60 + hours;
  812. // b. Set hours to ! RoundNumberToIncrement(fractionalHours, increment, roundingMode).
  813. hours = (double)round_number_to_increment(fractional_hours, increment, rounding_mode);
  814. // c. Set remainder to fractionalHours - hours.
  815. remainder = fractional_hours - hours;
  816. // d. Set minutes, seconds, milliseconds, microseconds, and nanoseconds to 0.
  817. minutes = 0;
  818. seconds = 0;
  819. milliseconds = 0;
  820. microseconds = 0;
  821. nanoseconds = 0;
  822. }
  823. // 14. Else if unit is "minute", then
  824. else if (unit == "minute"sv) {
  825. // a. Let fractionalMinutes be fractionalSeconds / 60 + minutes.
  826. auto fractional_minutes = fractional_seconds / 60 + minutes;
  827. // b. Set minutes to ! RoundNumberToIncrement(fractionalMinutes, increment, roundingMode).
  828. minutes = (double)round_number_to_increment(fractional_minutes, increment, rounding_mode);
  829. // c. Set remainder to fractionalMinutes - minutes.
  830. remainder = fractional_minutes - minutes;
  831. // d. Set seconds, milliseconds, microseconds, and nanoseconds to 0.
  832. seconds = 0;
  833. milliseconds = 0;
  834. microseconds = 0;
  835. nanoseconds = 0;
  836. }
  837. // 15. Else if unit is "second", then
  838. else if (unit == "second"sv) {
  839. // a. Set seconds to ! RoundNumberToIncrement(fractionalSeconds, increment, roundingMode).
  840. seconds = (double)round_number_to_increment(fractional_seconds, increment, rounding_mode);
  841. // b. Set remainder to fractionalSeconds - seconds.
  842. remainder = fractional_seconds - seconds;
  843. // c. Set milliseconds, microseconds, and nanoseconds to 0.
  844. milliseconds = 0;
  845. microseconds = 0;
  846. nanoseconds = 0;
  847. }
  848. // 16. Else if unit is "millisecond", then
  849. else if (unit == "millisecond"sv) {
  850. // a. Let fractionalMilliseconds be nanoseconds × 10^−6 + microseconds × 10^−3 + milliseconds.
  851. auto fractional_milliseconds = nanoseconds * 0.000001 + microseconds * 0.001 + milliseconds;
  852. // b. Set milliseconds to ! RoundNumberToIncrement(fractionalMilliseconds, increment, roundingMode).
  853. milliseconds = (double)round_number_to_increment(fractional_milliseconds, increment, rounding_mode);
  854. // c. Set remainder to fractionalMilliseconds - milliseconds.
  855. remainder = fractional_milliseconds - milliseconds;
  856. // d. Set microseconds and nanoseconds to 0.
  857. microseconds = 0;
  858. nanoseconds = 0;
  859. }
  860. // 17. Else if unit is "microsecond", then
  861. else if (unit == "microsecond"sv) {
  862. // a. Let fractionalMicroseconds be nanoseconds × 10^−3 + microseconds.
  863. auto fractional_microseconds = nanoseconds * 0.001 + microseconds;
  864. // b. Set microseconds to ! RoundNumberToIncrement(fractionalMicroseconds, increment, roundingMode).
  865. microseconds = (double)round_number_to_increment(fractional_microseconds, increment, rounding_mode);
  866. // c. Set remainder to fractionalMicroseconds - microseconds.
  867. remainder = fractional_microseconds - microseconds;
  868. // d. Set nanoseconds to 0.
  869. nanoseconds = 0;
  870. }
  871. // 18. Else,
  872. else {
  873. // a. Assert: unit is "nanosecond".
  874. VERIFY(unit == "nanosecond"sv);
  875. // b. Set remainder to nanoseconds.
  876. remainder = nanoseconds;
  877. // c. Set nanoseconds to ! RoundNumberToIncrement(nanoseconds, increment, roundingMode).
  878. nanoseconds = (double)round_number_to_increment(nanoseconds, increment, rounding_mode);
  879. // d. Set remainder to remainder − nanoseconds.
  880. remainder -= nanoseconds;
  881. }
  882. // Return the Record { [[Years]]: years, [[Months]]: months, [[Weeks]]: weeks, [[Days]]: days, [[Hours]]: hours, [[Minutes]]: minutes, [[Seconds]]: seconds, [[Milliseconds]]: milliseconds, [[Microseconds]]: microseconds, [[Nanoseconds]]: nanoseconds, [[Remainder]]: remainder }.
  883. return RoundedDuration { .years = years, .months = months, .weeks = weeks, .days = days, .hours = hours, .minutes = minutes, .seconds = seconds, .milliseconds = milliseconds, .microseconds = microseconds, .nanoseconds = nanoseconds, .remainder = remainder };
  884. }
  885. // 7.5.20 ToLimitedTemporalDuration ( temporalDurationLike, disallowedFields ), https://tc39.es/proposal-temporal/#sec-temporal-tolimitedtemporalduration
  886. ThrowCompletionOr<TemporalDuration> to_limited_temporal_duration(GlobalObject& global_object, Value temporal_duration_like, Vector<StringView> const& disallowed_fields)
  887. {
  888. auto& vm = global_object.vm();
  889. TemporalDuration duration;
  890. // 1. If Type(temporalDurationLike) is not Object, then
  891. if (!temporal_duration_like.is_object()) {
  892. // a. Let str be ? ToString(temporalDurationLike).
  893. auto str = TRY(temporal_duration_like.to_string(global_object));
  894. // b. Let duration be ? ParseTemporalDurationString(str).
  895. duration = TRY(parse_temporal_duration_string(global_object, str));
  896. }
  897. // 2. Else,
  898. else {
  899. // a. Let duration be ? ToTemporalDurationRecord(temporalDurationLike).
  900. duration = TRY(to_temporal_duration_record(global_object, temporal_duration_like.as_object()));
  901. }
  902. // 3. If ! IsValidDuration(duration.[[Years]], duration.[[Months]], duration.[[Weeks]], duration.[[Days]], duration.[[Hours]], duration.[[Minutes]], duration.[[Seconds]], duration.[[Milliseconds]], duration.[[Microseconds]], duration.[[Nanoseconds]]) is false, throw a RangeError exception.
  903. if (!is_valid_duration(duration.years, duration.months, duration.weeks, duration.days, duration.hours, duration.minutes, duration.seconds, duration.milliseconds, duration.microseconds, duration.nanoseconds))
  904. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidDuration);
  905. // 4. For each row of Table 7, except the header row, in table order, do
  906. for (auto& [internal_slot, property] : temporal_duration_like_properties<TemporalDuration, double>(vm)) {
  907. // a. Let prop be the Property value of the current row.
  908. // b. Let value be duration's internal slot whose name is the Internal Slot value of the current row.
  909. auto value = duration.*internal_slot;
  910. // If value is not 0 and disallowedFields contains prop, then
  911. if (value != 0 && disallowed_fields.contains_slow(property.as_string())) {
  912. // i. Throw a RangeError exception.
  913. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidDurationPropertyValueNonZero, property.as_string(), value);
  914. }
  915. }
  916. // 5. Return duration.
  917. return duration;
  918. }
  919. // 7.5.21 TemporalDurationToString ( years, months, weeks, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds, precision ), https://tc39.es/proposal-temporal/#sec-temporal-temporaldurationtostring
  920. String temporal_duration_to_string(double years, double months, double weeks, double days, double hours, double minutes, double seconds, double milliseconds, double microseconds, double nanoseconds, Variant<StringView, u8> const& precision)
  921. {
  922. // 1. Assert: precision is not "minute".
  923. if (precision.has<StringView>())
  924. VERIFY(precision.get<StringView>() != "minute"sv);
  925. // 2. Set seconds to the mathematical value of seconds.
  926. // 3. Set milliseconds to the mathematical value of milliseconds.
  927. // 4. Set microseconds to the mathematical value of microseconds.
  928. // 5. Set nanoseconds to the mathematical value of nanoseconds.
  929. // 6. Let sign be ! DurationSign(years, months, weeks, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds).
  930. auto sign = duration_sign(years, months, weeks, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds);
  931. // 7. Set microseconds to microseconds + the integral part of nanoseconds / 1000.
  932. microseconds += trunc(nanoseconds / 1000);
  933. // 8. Set nanoseconds to remainder(nanoseconds, 1000).
  934. nanoseconds = fmod(nanoseconds, 1000);
  935. // 9. Set milliseconds to milliseconds + the integral part of microseconds / 1000.
  936. milliseconds += trunc(microseconds / 1000);
  937. // 10. Set microseconds to remainder(microseconds, 1000).
  938. microseconds = fmod(microseconds, 1000);
  939. // 11. Set seconds to seconds + the integral part of milliseconds / 1000.
  940. seconds += trunc(milliseconds / 1000);
  941. // 12. Set milliseconds to remainder(milliseconds, 1000).
  942. milliseconds = fmod(milliseconds, 1000);
  943. // 13. Let datePart be "".
  944. StringBuilder date_part;
  945. // 14. If years is not 0, then
  946. if (years != 0) {
  947. // a. Set datePart to the string concatenation of abs(years) formatted as a decimal number and the code unit 0x0059 (LATIN CAPITAL LETTER Y).
  948. date_part.appendff("{}", fabs(years));
  949. date_part.append('Y');
  950. }
  951. // 15. If months is not 0, then
  952. if (months != 0) {
  953. // a. Set datePart to the string concatenation of datePart, abs(months) formatted as a decimal number, and the code unit 0x004D (LATIN CAPITAL LETTER M).
  954. date_part.appendff("{}", fabs(months));
  955. date_part.append('M');
  956. }
  957. // 16. If weeks is not 0, then
  958. if (weeks != 0) {
  959. // a. Set datePart to the string concatenation of datePart, abs(weeks) formatted as a decimal number, and the code unit 0x0057 (LATIN CAPITAL LETTER W).
  960. date_part.appendff("{}", fabs(weeks));
  961. date_part.append('W');
  962. }
  963. // 17. If days is not 0, then
  964. if (days != 0) {
  965. // a. Set datePart to the string concatenation of datePart, abs(days) formatted as a decimal number, and the code unit 0x0044 (LATIN CAPITAL LETTER D).
  966. date_part.appendff("{}", fabs(days));
  967. date_part.append('D');
  968. }
  969. // 18. Let timePart be "".
  970. StringBuilder time_part;
  971. // 19. If hours is not 0, then
  972. if (hours != 0) {
  973. // a. Set timePart to the string concatenation of abs(hours) formatted as a decimal number and the code unit 0x0048 (LATIN CAPITAL LETTER H).
  974. time_part.appendff("{}", fabs(hours));
  975. time_part.append('H');
  976. }
  977. // 20. If minutes is not 0, then
  978. if (minutes != 0) {
  979. // a. Set timePart to the string concatenation of timePart, abs(minutes) formatted as a decimal number, and the code unit 0x004D (LATIN CAPITAL LETTER M).
  980. time_part.appendff("{}", fabs(minutes));
  981. time_part.append('M');
  982. }
  983. // 21. If any of seconds, milliseconds, microseconds, and nanoseconds are not 0; or years, months, weeks, days, hours, and minutes are all 0, then
  984. if ((seconds != 0 || milliseconds != 0 || microseconds != 0 || nanoseconds != 0) || (years == 0 && months == 0 && weeks == 0 && days == 0 && hours == 0 && minutes == 0)) {
  985. // a. Let fraction be abs(milliseconds) × 10^6 + abs(microseconds) × 10^3 + abs(nanoseconds).
  986. auto fraction = fabs(milliseconds) * 1'000'000 + fabs(microseconds) * 1'000 + fabs(nanoseconds);
  987. // b. Let decimalPart be fraction formatted as a nine-digit decimal number, padded to the left with zeroes if necessary.
  988. // NOTE: padding with zeros leads to weird results when applied to a double. Not sure if that's a bug in AK/Format.h or if I'm doing this wrong.
  989. auto decimal_part = String::formatted("{:09}", (u64)fraction);
  990. // c. If precision is "auto", then
  991. if (precision.has<StringView>() && precision.get<StringView>() == "auto"sv) {
  992. // i. Set decimalPart to the longest possible substring of decimalPart starting at position 0 and not ending with the code unit 0x0030 (DIGIT ZERO).
  993. // NOTE: trim() would keep the left-most 0.
  994. while (decimal_part.ends_with('0'))
  995. decimal_part = decimal_part.substring(0, decimal_part.length() - 1);
  996. }
  997. // d. Else if precision = 0, then
  998. else if (precision.get<u8>() == 0) {
  999. // i. Set decimalPart to "".
  1000. decimal_part = String::empty();
  1001. }
  1002. // e. Else,
  1003. else {
  1004. // i. Set decimalPart to the substring of decimalPart from 0 to precision.
  1005. decimal_part = decimal_part.substring(0, precision.get<u8>());
  1006. }
  1007. // f. Let secondsPart be abs(seconds) formatted as a decimal number.
  1008. StringBuilder seconds_part;
  1009. seconds_part.appendff("{}", fabs(seconds));
  1010. // g. If decimalPart is not "", then
  1011. if (!decimal_part.is_empty()) {
  1012. // i. Set secondsPart to the string-concatenation of secondsPart, the code unit 0x002E (FULL STOP), and decimalPart.
  1013. seconds_part.append('.');
  1014. seconds_part.append(decimal_part);
  1015. }
  1016. // h. Set timePart to the string concatenation of timePart, secondsPart, and the code unit 0x0053 (LATIN CAPITAL LETTER S).
  1017. time_part.append(seconds_part.string_view());
  1018. time_part.append('S');
  1019. }
  1020. // 22. Let signPart be the code unit 0x002D (HYPHEN-MINUS) if sign < 0, and otherwise the empty String.
  1021. auto sign_part = sign < 0 ? "-"sv : ""sv;
  1022. // 23. Let result be the string concatenation of signPart, the code unit 0x0050 (LATIN CAPITAL LETTER P) and datePart.
  1023. StringBuilder result;
  1024. result.append(sign_part);
  1025. result.append('P');
  1026. result.append(date_part.string_view());
  1027. // 24. If timePart is not "", then
  1028. if (!time_part.is_empty()) {
  1029. // a. Set result to the string concatenation of result, the code unit 0x0054 (LATIN CAPITAL LETTER T), and timePart.
  1030. result.append('T');
  1031. result.append(time_part.string_view());
  1032. }
  1033. // 25. Return result.
  1034. return result.to_string();
  1035. }
  1036. }