Duration.cpp 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317
  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 ? ToTemporalDateTime(relativeTo).
  411. PlainDateTime* relative_to_plain_date_time = TRY(to_temporal_date_time(global_object, relative_to));
  412. relative_to = relative_to_plain_date_time;
  413. // b. Let calendar be relativeTo.[[Calendar]].
  414. calendar = &relative_to_plain_date_time->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<PlainDateTime>(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<PlainDateTime>(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<PlainDateTime>(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<PlainDateTime>(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<PlainDateTime>(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, PlainDateTime& relative_to, Duration& duration)
  533. {
  534. // 1. Assert: Type(relativeTo) is Object.
  535. // 2. Assert: relativeTo has an [[InitializedTemporalDateTime]] internal slot.
  536. // 3. Let options be ! OrdinaryObjectCreate(null).
  537. auto* options = Object::create(global_object, nullptr);
  538. // 4. Let later be ? CalendarDateAdd(calendar, relativeTo, duration, options).
  539. auto* later = TRY(calendar_date_add(global_object, calendar, &relative_to, duration, options));
  540. // 5. Let days be ? DaysUntil(relativeTo, later).
  541. auto days = days_until(global_object, relative_to, *later);
  542. // 6. Let dateTime be ? CreateTemporalDateTime(later.[[ISOYear]], later.[[ISOMonth]], later.[[ISODay]], relativeTo.[[ISOHour]], relativeTo.[[ISOMinute]], relativeTo.[[ISOSecond]], relativeTo.[[ISOMillisecond]], relativeTo.[[ISOMicrosecond]], relativeTo.[[ISONanosecond]], relativeTo.[[Calendar]]).
  543. auto* date_time = TRY(create_temporal_date_time(global_object, later->iso_year(), later->iso_month(), later->iso_day(), relative_to.iso_hour(), relative_to.iso_minute(), relative_to.iso_second(), relative_to.iso_millisecond(), relative_to.iso_microsecond(), relative_to.iso_nanosecond(), relative_to.calendar()));
  544. // 7. Return the Record { [[RelativeTo]]: dateTime, [[Days]]: days }.
  545. return MoveRelativeDateResult { .relative_to = make_handle(date_time), .days = days };
  546. }
  547. // 7.5.17 MoveRelativeZonedDateTime ( zonedDateTime, years, months, weeks, days ), https://tc39.es/proposal-temporal/#sec-temporal-moverelativezoneddatetime
  548. ThrowCompletionOr<ZonedDateTime*> move_relative_zoned_date_time(GlobalObject& global_object, ZonedDateTime& zoned_date_time, double years, double months, double weeks, double days)
  549. {
  550. // 1. Let intermediateNs be ? AddZonedDateTime(zonedDateTime.[[Nanoseconds]], zonedDateTime.[[TimeZone]], zonedDateTime.[[Calendar]], years, months, weeks, days, 0, 0, 0, 0, 0, 0).
  551. 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));
  552. // 2. Return ! CreateTemporalZonedDateTime(intermediateNs, zonedDateTime.[[TimeZone]], zonedDateTime.[[Calendar]]).
  553. return MUST(create_temporal_zoned_date_time(global_object, *intermediate_ns, zoned_date_time.time_zone(), zoned_date_time.calendar()));
  554. }
  555. // 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
  556. 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)
  557. {
  558. auto& vm = global_object.vm();
  559. Object* calendar = nullptr;
  560. double fractional_seconds = 0;
  561. // 1. If relativeTo is not present, set relativeTo to undefined.
  562. // NOTE: `relative_to_object`, `relative_to_date`, and `relative_to` in the various code paths below
  563. // are all the same as far as the spec is concerned, but the latter two are more strictly typed for convenience.
  564. // The `_date` suffix is used as relativeTo is guaranteed to be a PlainDateTime object or undefined after step 5
  565. // (i.e. PlainDateTime*), but a PlainDate object is assigned in a couple of cases.
  566. PlainDateTime* relative_to = nullptr;
  567. // 2. Let years, months, weeks, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds, and increment each be the mathematical values of themselves.
  568. // FIXME: assuming "smallestUnit" as the option name here leads to confusing error messages in some cases:
  569. // > new Temporal.Duration().total({ unit: "month" })
  570. // Uncaught exception: [RangeError] month is not a valid value for option smallestUnit
  571. // 3. If unit is "year", "month", or "week", and relativeTo is undefined, then
  572. if (unit.is_one_of("year"sv, "month"sv, "week"sv) && !relative_to_object) {
  573. // a. Throw a RangeError exception.
  574. return vm.throw_completion<RangeError>(global_object, ErrorType::OptionIsNotValidValue, unit, "smallestUnit"sv);
  575. }
  576. // 4. Let zonedRelativeTo be undefined.
  577. ZonedDateTime* zoned_relative_to = nullptr;
  578. // 5. If relativeTo is not undefined, then
  579. if (relative_to_object) {
  580. // a. If relativeTo has an [[InitializedTemporalZonedDateTime]] internal slot, then
  581. if (is<ZonedDateTime>(relative_to_object)) {
  582. auto* relative_to_zoned_date_time = static_cast<ZonedDateTime*>(relative_to_object);
  583. // i. Let instant be ! CreateTemporalInstant(relativeTo.[[Nanoseconds]]).
  584. auto* instant = MUST(create_temporal_instant(global_object, relative_to_zoned_date_time->nanoseconds()));
  585. // ii. Set zonedRelativeTo to relativeTo.
  586. zoned_relative_to = relative_to_zoned_date_time;
  587. // iii. Set relativeTo to ? BuiltinTimeZoneGetPlainDateTimeFor(relativeTo.[[TimeZone]], instant, relativeTo.[[Calendar]]).
  588. relative_to = 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()));
  589. }
  590. // b. Else,
  591. else {
  592. // i. Assert: relativeTo has an [[InitializedTemporalDateTime]] internal slot.
  593. VERIFY(is<PlainDateTime>(relative_to_object));
  594. relative_to = static_cast<PlainDateTime*>(relative_to_object);
  595. }
  596. // c. Let calendar be relativeTo.[[Calendar]].
  597. calendar = &relative_to->calendar();
  598. }
  599. // 6. If unit is one of "year", "month", "week", or "day", then
  600. if (unit.is_one_of("year"sv, "month"sv, "week"sv, "day"sv)) {
  601. auto* nanoseconds_bigint = js_bigint(vm, Crypto::SignedBigInteger::create_from((i64)nanoseconds));
  602. // a. Let nanoseconds be ! TotalDurationNanoseconds(0, hours, minutes, seconds, milliseconds, microseconds, nanoseconds, 0).
  603. nanoseconds_bigint = total_duration_nanoseconds(global_object, 0, hours, minutes, seconds, milliseconds, microseconds, *nanoseconds_bigint, 0);
  604. // b. Let intermediate be undefined.
  605. ZonedDateTime* intermediate = nullptr;
  606. // c. If zonedRelativeTo is not undefined, then
  607. if (zoned_relative_to) {
  608. // i. Let intermediate be ? MoveRelativeZonedDateTime(zonedRelativeTo, years, months, weeks, days).
  609. intermediate = TRY(move_relative_zoned_date_time(global_object, *zoned_relative_to, years, months, weeks, days));
  610. }
  611. // d. Let result be ? NanosecondsToDays(nanoseconds, intermediate).
  612. auto result = TRY(nanoseconds_to_days(global_object, *nanoseconds_bigint, intermediate));
  613. // e. Set days to days + result.[[Days]] + result.[[Nanoseconds]] / result.[[DayLength]].
  614. auto nanoseconds_division_result = result.nanoseconds.cell()->big_integer().divided_by(Crypto::UnsignedBigInteger::create_from((u64)result.day_length));
  615. days += result.days + nanoseconds_division_result.quotient.to_double() + nanoseconds_division_result.remainder.to_double() / result.day_length;
  616. // f. Set hours, minutes, seconds, milliseconds, microseconds, and nanoseconds to 0.
  617. hours = 0;
  618. minutes = 0;
  619. seconds = 0;
  620. milliseconds = 0;
  621. microseconds = 0;
  622. nanoseconds = 0;
  623. }
  624. // 7. Else,
  625. else {
  626. // a. Let fractionalSeconds be nanoseconds × 10^−9 + microseconds × 10^−6 + milliseconds × 10^−3 + seconds.
  627. fractional_seconds = nanoseconds * 0.000000001 + microseconds * 0.000001 + milliseconds * 0.001 + seconds;
  628. }
  629. // 8. Let remainder be undefined.
  630. double remainder = 0;
  631. // 9. If unit is "year", then
  632. if (unit == "year"sv) {
  633. VERIFY(relative_to);
  634. // a. Let yearsDuration be ? CreateTemporalDuration(years, 0, 0, 0, 0, 0, 0, 0, 0, 0).
  635. auto* years_duration = TRY(create_temporal_duration(global_object, years, 0, 0, 0, 0, 0, 0, 0, 0, 0));
  636. // b. Let dateAdd be ? GetMethod(calendar, "dateAdd").
  637. auto* date_add = TRY(Value(calendar).get_method(global_object, vm.names.dateAdd));
  638. // c. Let firstAddOptions be ! OrdinaryObjectCreate(null).
  639. auto* first_add_options = Object::create(global_object, nullptr);
  640. // d. Let yearsLater be ? CalendarDateAdd(calendar, relativeTo, yearsDuration, firstAddOptions, dateAdd).
  641. auto* years_later = TRY(calendar_date_add(global_object, *calendar, relative_to, *years_duration, first_add_options, date_add));
  642. // e. Let yearsMonthsWeeks be ? CreateTemporalDuration(years, months, weeks, 0, 0, 0, 0, 0, 0, 0).
  643. auto* years_months_weeks = TRY(create_temporal_duration(global_object, years, months, weeks, 0, 0, 0, 0, 0, 0, 0));
  644. // f. Let secondAddOptions be ! OrdinaryObjectCreate(null).
  645. auto* second_add_options = Object::create(global_object, nullptr);
  646. // g. Let yearsMonthsWeeksLater be ? CalendarDateAdd(calendar, relativeTo, yearsMonthsWeeks, secondAddOptions, dateAdd).
  647. auto* years_months_weeks_later = TRY(calendar_date_add(global_object, *calendar, relative_to, *years_months_weeks, second_add_options, date_add));
  648. // h. Let monthsWeeksInDays be ? DaysUntil(yearsLater, yearsMonthsWeeksLater).
  649. auto months_weeks_in_days = days_until(global_object, *years_later, *years_months_weeks_later);
  650. // i. Set relativeTo to yearsLater.
  651. auto* relative_to_date = years_later;
  652. // j. Let days be days + monthsWeeksInDays.
  653. days += months_weeks_in_days;
  654. // k. Let daysDuration be ? CreateTemporalDuration(0, 0, 0, days, 0, 0, 0, 0, 0, 0).
  655. auto* days_duration = TRY(create_temporal_duration(global_object, 0, 0, 0, days, 0, 0, 0, 0, 0, 0));
  656. // l. Let thirdAddOptions be ! OrdinaryObjectCreate(null).
  657. auto* third_add_options = Object::create(global_object, nullptr);
  658. // m. Let daysLater be ? CalendarDateAdd(calendar, relativeTo, daysDuration, thirdAddOptions, dateAdd).
  659. auto* days_later = TRY(calendar_date_add(global_object, *calendar, relative_to_date, *days_duration, third_add_options, date_add));
  660. // n. Let untilOptions be ! OrdinaryObjectCreate(null).
  661. auto* until_options = Object::create(global_object, nullptr);
  662. // o. Perform ! CreateDataPropertyOrThrow(untilOptions, "largestUnit", "year").
  663. MUST(until_options->create_data_property_or_throw(vm.names.largestUnit, js_string(vm, "year"sv)));
  664. // p. Let timePassed be ? CalendarDateUntil(calendar, relativeTo, daysLater, untilOptions).
  665. auto* time_passed = TRY(calendar_date_until(global_object, *calendar, relative_to_date, days_later, *until_options));
  666. // q. Let yearsPassed be timePassed.[[Years]].
  667. auto years_passed = time_passed->years();
  668. // r. Set years to years + yearsPassed.
  669. years += years_passed;
  670. // s. Let oldRelativeTo be relativeTo.
  671. auto* old_relative_to_date = relative_to_date;
  672. // t. Let yearsDuration be ? CreateTemporalDuration(yearsPassed, 0, 0, 0, 0, 0, 0, 0, 0, 0).
  673. years_duration = TRY(create_temporal_duration(global_object, years_passed, 0, 0, 0, 0, 0, 0, 0, 0, 0));
  674. // u. Let fourthAddOptions be ! OrdinaryObjectCreate(null).
  675. auto* fourth_add_options = Object::create(global_object, nullptr);
  676. // v. Set relativeTo to ? CalendarDateAdd(calendar, relativeTo, yearsDuration, fourthAddOptions, dateAdd).
  677. relative_to_date = TRY(calendar_date_add(global_object, *calendar, relative_to_date, *years_duration, fourth_add_options, date_add));
  678. // w. Let daysPassed be ? DaysUntil(oldRelativeTo, relativeTo).
  679. auto days_passed = days_until(global_object, *old_relative_to_date, *relative_to_date);
  680. // x. Set days to days - daysPassed.
  681. days -= days_passed;
  682. // y. Let sign be ! Sign(days).
  683. auto sign = JS::Temporal::sign(days);
  684. // z. If sign is 0, set sign to 1.
  685. if (sign == 0)
  686. sign = 1;
  687. // aa. Let oneYear be ? CreateTemporalDuration(sign, 0, 0, 0, 0, 0, 0, 0, 0, 0).
  688. auto* one_year = TRY(create_temporal_duration(global_object, sign, 0, 0, 0, 0, 0, 0, 0, 0, 0));
  689. // ab. Set relativeTo to ! CreateTemporalDateTime(relativeTo.[[ISOYear]], relativeTo.[[ISOMonth]], relativeTo.[[ISODay]], 0, 0, 0, 0, 0, 0, relativeTo.[[Calendar]]).
  690. relative_to = MUST(create_temporal_date_time(global_object, relative_to_date->iso_year(), relative_to_date->iso_month(), relative_to_date->iso_day(), 0, 0, 0, 0, 0, 0, relative_to->calendar()));
  691. // ac. Let moveResult be ? MoveRelativeDate(calendar, relativeTo, oneYear).
  692. auto move_result = TRY(move_relative_date(global_object, *calendar, *relative_to, *one_year));
  693. // ad. Let oneYearDays be moveResult.[[Days]].
  694. auto one_year_days = move_result.days;
  695. // ae. Let fractionalYears be years + days / abs(oneYearDays).
  696. auto fractional_years = years + days / fabs(one_year_days);
  697. // af. Set years to ! RoundNumberToIncrement(fractionalYears, increment, roundingMode).
  698. years = (double)round_number_to_increment(fractional_years, increment, rounding_mode);
  699. // ag. Set remainder to fractionalYears - years.
  700. remainder = fractional_years - years;
  701. // ah. Set months, weeks, and days to 0.
  702. months = 0;
  703. weeks = 0;
  704. days = 0;
  705. }
  706. // 10. Else if unit is "month", then
  707. else if (unit == "month"sv) {
  708. VERIFY(relative_to);
  709. // a. Let yearsMonths be ? CreateTemporalDuration(years, months, 0, 0, 0, 0, 0, 0, 0, 0).
  710. auto* years_months = TRY(create_temporal_duration(global_object, years, months, 0, 0, 0, 0, 0, 0, 0, 0));
  711. // b. Let dateAdd be ? GetMethod(calendar, "dateAdd").
  712. auto* date_add = TRY(Value(calendar).get_method(global_object, vm.names.dateAdd));
  713. // c. Let firstAddOptions be ! OrdinaryObjectCreate(null).
  714. auto* first_add_options = Object::create(global_object, nullptr);
  715. // d. Let yearsMonthsLater be ? CalendarDateAdd(calendar, relativeTo, yearsMonths, firstAddOptions, dateAdd).
  716. auto* years_months_later = TRY(calendar_date_add(global_object, *calendar, relative_to, *years_months, first_add_options, date_add));
  717. // e. Let yearsMonthsWeeks be ? CreateTemporalDuration(years, months, weeks, 0, 0, 0, 0, 0, 0, 0).
  718. auto* years_months_weeks = TRY(create_temporal_duration(global_object, years, months, weeks, 0, 0, 0, 0, 0, 0, 0));
  719. // f. Let secondAddOptions be ! OrdinaryObjectCreate(null).
  720. auto* seconds_add_options = Object::create(global_object, nullptr);
  721. // g. Let yearsMonthsWeeksLater be ? CalendarDateAdd(calendar, relativeTo, yearsMonthsWeeks, secondAddOptions, dateAdd).
  722. auto* years_months_weeks_later = TRY(calendar_date_add(global_object, *calendar, relative_to, *years_months_weeks, seconds_add_options, date_add));
  723. // h. Let weeksInDays be ? DaysUntil(yearsMonthsLater, yearsMonthsWeeksLater).
  724. auto weeks_in_days = days_until(global_object, *years_months_later, *years_months_weeks_later);
  725. // i. Set relativeTo to yearsMonthsLater.
  726. auto* relative_to_date = years_months_later;
  727. // j. Let days be days + weeksInDays.
  728. days += weeks_in_days;
  729. // k. Let sign be ! Sign(days).
  730. auto sign = JS::Temporal::sign(days);
  731. // l. If sign is 0, set sign to 1.
  732. if (sign == 0)
  733. sign = 1;
  734. // m. Let oneMonth be ? CreateTemporalDuration(0, sign, 0, 0, 0, 0, 0, 0, 0, 0).
  735. auto* one_month = TRY(create_temporal_duration(global_object, 0, sign, 0, 0, 0, 0, 0, 0, 0, 0));
  736. // n. Set relativeTo to ! CreateTemporalDateTime(relativeTo.[[ISOYear]], relativeTo.[[ISOMonth]], relativeTo.[[ISODay]], 0, 0, 0, 0, 0, 0, relativeTo.[[Calendar]]).
  737. relative_to = MUST(create_temporal_date_time(global_object, relative_to_date->iso_year(), relative_to_date->iso_month(), relative_to_date->iso_day(), 0, 0, 0, 0, 0, 0, relative_to_date->calendar()));
  738. // o. Let moveResult be ? MoveRelativeDate(calendar, relativeTo, oneMonth).
  739. auto move_result = TRY(move_relative_date(global_object, *calendar, *relative_to, *one_month));
  740. // p. Set relativeTo to moveResult.[[RelativeTo]].
  741. relative_to = move_result.relative_to.cell();
  742. // q. Let oneMonthDays be moveResult.[[Days]].
  743. auto one_month_days = move_result.days;
  744. // r. Repeat, while abs(days) ≥ abs(oneMonthDays),
  745. while (fabs(days) >= fabs(one_month_days)) {
  746. // i. Set months to months + sign.
  747. months += sign;
  748. // ii. Set days to days − oneMonthDays.
  749. days -= one_month_days;
  750. // iii. Set moveResult to ? MoveRelativeDate(calendar, relativeTo, oneMonth).
  751. move_result = TRY(move_relative_date(global_object, *calendar, *relative_to, *one_month));
  752. // iv. Set relativeTo to moveResult.[[RelativeTo]].
  753. relative_to = move_result.relative_to.cell();
  754. // v. Set oneMonthDays to moveResult.[[Days]].
  755. one_month_days = move_result.days;
  756. }
  757. // s. Let fractionalMonths be months + days / abs(oneMonthDays).
  758. auto fractional_months = months + days / fabs(one_month_days);
  759. // t. Set months to ! RoundNumberToIncrement(fractionalMonths, increment, roundingMode).
  760. months = (double)round_number_to_increment(fractional_months, increment, rounding_mode);
  761. // u. Set remainder to fractionalMonths - months.
  762. remainder = fractional_months - months;
  763. // v. Set weeks and days to 0.
  764. weeks = 0;
  765. days = 0;
  766. }
  767. // 11. Else if unit is "week", then
  768. else if (unit == "week"sv) {
  769. VERIFY(relative_to);
  770. // a. Let sign be ! Sign(days).
  771. auto sign = JS::Temporal::sign(days);
  772. // b. If sign is 0, set sign to 1.
  773. if (sign == 0)
  774. sign = 1;
  775. // c. Let oneWeek be ? CreateTemporalDuration(0, 0, sign, 0, 0, 0, 0, 0, 0, 0).
  776. auto* one_week = TRY(create_temporal_duration(global_object, 0, 0, sign, 0, 0, 0, 0, 0, 0, 0));
  777. // d. Let moveResult be ? MoveRelativeDate(calendar, relativeTo, oneWeek).
  778. auto move_result = TRY(move_relative_date(global_object, *calendar, *relative_to, *one_week));
  779. // e. Set relativeTo to moveResult.[[RelativeTo]].
  780. relative_to = move_result.relative_to.cell();
  781. // f. Let oneWeekDays be moveResult.[[Days]].
  782. auto one_week_days = move_result.days;
  783. // g. Repeat, while abs(days) ≥ abs(oneWeekDays),
  784. while (fabs(days) >= fabs(one_week_days)) {
  785. // i. Set weeks to weeks + sign.
  786. weeks += sign;
  787. // ii. Set days to days − oneWeekDays.
  788. days -= one_week_days;
  789. // iii. Set moveResult to ? MoveRelativeDate(calendar, relativeTo, oneWeek).
  790. move_result = TRY(move_relative_date(global_object, *calendar, *relative_to, *one_week));
  791. // iv. Set relativeTo to moveResult.[[RelativeTo]].
  792. relative_to = move_result.relative_to.cell();
  793. // v. Set oneWeekDays to moveResult.[[Days]].
  794. one_week_days = move_result.days;
  795. }
  796. // h. Let fractionalWeeks be weeks + days / abs(oneWeekDays).
  797. auto fractional_weeks = weeks + days / fabs(one_week_days);
  798. // i. Set weeks to ! RoundNumberToIncrement(fractionalWeeks, increment, roundingMode).
  799. weeks = (double)round_number_to_increment(fractional_weeks, increment, rounding_mode);
  800. // j. Set remainder to fractionalWeeks - weeks.
  801. remainder = fractional_weeks - weeks;
  802. // k. Set days to 0.
  803. days = 0;
  804. }
  805. // 12. Else if unit is "day", then
  806. else if (unit == "day"sv) {
  807. // a. Let fractionalDays be days.
  808. auto fractional_days = days;
  809. // b. Set days to ! RoundNumberToIncrement(days, increment, roundingMode).
  810. days = (double)round_number_to_increment(days, increment, rounding_mode);
  811. // c. Set remainder to fractionalDays - days.
  812. remainder = fractional_days - days;
  813. }
  814. // 13. Else if unit is "hour", then
  815. else if (unit == "hour"sv) {
  816. // a. Let fractionalHours be (fractionalSeconds / 60 + minutes) / 60 + hours.
  817. auto fractional_hours = (fractional_seconds / 60 + minutes) / 60 + hours;
  818. // b. Set hours to ! RoundNumberToIncrement(fractionalHours, increment, roundingMode).
  819. hours = (double)round_number_to_increment(fractional_hours, increment, rounding_mode);
  820. // c. Set remainder to fractionalHours - hours.
  821. remainder = fractional_hours - hours;
  822. // d. Set minutes, seconds, milliseconds, microseconds, and nanoseconds to 0.
  823. minutes = 0;
  824. seconds = 0;
  825. milliseconds = 0;
  826. microseconds = 0;
  827. nanoseconds = 0;
  828. }
  829. // 14. Else if unit is "minute", then
  830. else if (unit == "minute"sv) {
  831. // a. Let fractionalMinutes be fractionalSeconds / 60 + minutes.
  832. auto fractional_minutes = fractional_seconds / 60 + minutes;
  833. // b. Set minutes to ! RoundNumberToIncrement(fractionalMinutes, increment, roundingMode).
  834. minutes = (double)round_number_to_increment(fractional_minutes, increment, rounding_mode);
  835. // c. Set remainder to fractionalMinutes - minutes.
  836. remainder = fractional_minutes - minutes;
  837. // d. Set seconds, milliseconds, microseconds, and nanoseconds to 0.
  838. seconds = 0;
  839. milliseconds = 0;
  840. microseconds = 0;
  841. nanoseconds = 0;
  842. }
  843. // 15. Else if unit is "second", then
  844. else if (unit == "second"sv) {
  845. // a. Set seconds to ! RoundNumberToIncrement(fractionalSeconds, increment, roundingMode).
  846. seconds = (double)round_number_to_increment(fractional_seconds, increment, rounding_mode);
  847. // b. Set remainder to fractionalSeconds - seconds.
  848. remainder = fractional_seconds - seconds;
  849. // c. Set milliseconds, microseconds, and nanoseconds to 0.
  850. milliseconds = 0;
  851. microseconds = 0;
  852. nanoseconds = 0;
  853. }
  854. // 16. Else if unit is "millisecond", then
  855. else if (unit == "millisecond"sv) {
  856. // a. Let fractionalMilliseconds be nanoseconds × 10^−6 + microseconds × 10^−3 + milliseconds.
  857. auto fractional_milliseconds = nanoseconds * 0.000001 + microseconds * 0.001 + milliseconds;
  858. // b. Set milliseconds to ! RoundNumberToIncrement(fractionalMilliseconds, increment, roundingMode).
  859. milliseconds = (double)round_number_to_increment(fractional_milliseconds, increment, rounding_mode);
  860. // c. Set remainder to fractionalMilliseconds - milliseconds.
  861. remainder = fractional_milliseconds - milliseconds;
  862. // d. Set microseconds and nanoseconds to 0.
  863. microseconds = 0;
  864. nanoseconds = 0;
  865. }
  866. // 17. Else if unit is "microsecond", then
  867. else if (unit == "microsecond"sv) {
  868. // a. Let fractionalMicroseconds be nanoseconds × 10^−3 + microseconds.
  869. auto fractional_microseconds = nanoseconds * 0.001 + microseconds;
  870. // b. Set microseconds to ! RoundNumberToIncrement(fractionalMicroseconds, increment, roundingMode).
  871. microseconds = (double)round_number_to_increment(fractional_microseconds, increment, rounding_mode);
  872. // c. Set remainder to fractionalMicroseconds - microseconds.
  873. remainder = fractional_microseconds - microseconds;
  874. // d. Set nanoseconds to 0.
  875. nanoseconds = 0;
  876. }
  877. // 18. Else,
  878. else {
  879. // a. Assert: unit is "nanosecond".
  880. VERIFY(unit == "nanosecond"sv);
  881. // b. Set remainder to nanoseconds.
  882. remainder = nanoseconds;
  883. // c. Set nanoseconds to ! RoundNumberToIncrement(nanoseconds, increment, roundingMode).
  884. nanoseconds = (double)round_number_to_increment(nanoseconds, increment, rounding_mode);
  885. // d. Set remainder to remainder − nanoseconds.
  886. remainder -= nanoseconds;
  887. }
  888. // 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 }.
  889. return RoundedDuration { .years = years, .months = months, .weeks = weeks, .days = days, .hours = hours, .minutes = minutes, .seconds = seconds, .milliseconds = milliseconds, .microseconds = microseconds, .nanoseconds = nanoseconds, .remainder = remainder };
  890. }
  891. // 7.5.20 ToLimitedTemporalDuration ( temporalDurationLike, disallowedFields ),https://tc39.es/proposal-temporal/#sec-temporal-tolimitedtemporalduration
  892. ThrowCompletionOr<TemporalDuration> to_limited_temporal_duration(GlobalObject& global_object, Value temporal_duration_like, Vector<StringView> const& disallowed_fields)
  893. {
  894. auto& vm = global_object.vm();
  895. TemporalDuration duration;
  896. // 1. If Type(temporalDurationLike) is not Object, then
  897. if (!temporal_duration_like.is_object()) {
  898. // a. Let str be ? ToString(temporalDurationLike).
  899. auto str = TRY(temporal_duration_like.to_string(global_object));
  900. // b. Let duration be ? ParseTemporalDurationString(str).
  901. duration = TRY(parse_temporal_duration_string(global_object, str));
  902. }
  903. // 2. Else,
  904. else {
  905. // a. Let duration be ? ToTemporalDurationRecord(temporalDurationLike).
  906. duration = TRY(to_temporal_duration_record(global_object, temporal_duration_like.as_object()));
  907. }
  908. // 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.
  909. if (!is_valid_duration(duration.years, duration.months, duration.weeks, duration.days, duration.hours, duration.minutes, duration.seconds, duration.milliseconds, duration.microseconds, duration.nanoseconds))
  910. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidDuration);
  911. // 4. For each row of Table 7, except the header row, in table order, do
  912. for (auto& [internal_slot, property] : temporal_duration_like_properties<TemporalDuration, double>(vm)) {
  913. // a. Let prop be the Property value of the current row.
  914. // b. Let value be duration's internal slot whose name is the Internal Slot value of the current row.
  915. auto value = duration.*internal_slot;
  916. // If value is not 0 and disallowedFields contains prop, then
  917. if (value != 0 && disallowed_fields.contains_slow(property.as_string())) {
  918. // i. Throw a RangeError exception.
  919. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidDurationPropertyValueNonZero, property.as_string(), value);
  920. }
  921. }
  922. // 5. Return duration.
  923. return duration;
  924. }
  925. // 7.5.21 TemporalDurationToString ( years, months, weeks, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds, precision ), https://tc39.es/proposal-temporal/#sec-temporal-temporaldurationtostring
  926. 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)
  927. {
  928. // 1. Assert: precision is not "minute".
  929. if (precision.has<StringView>())
  930. VERIFY(precision.get<StringView>() != "minute"sv);
  931. // 2. Set seconds to the mathematical value of seconds.
  932. // 3. Set milliseconds to the mathematical value of milliseconds.
  933. // 4. Set microseconds to the mathematical value of microseconds.
  934. // 5. Set nanoseconds to the mathematical value of nanoseconds.
  935. // 6. Let sign be ! DurationSign(years, months, weeks, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds).
  936. auto sign = duration_sign(years, months, weeks, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds);
  937. // 7. Set microseconds to microseconds + the integral part of nanoseconds / 1000.
  938. microseconds += trunc(nanoseconds / 1000);
  939. // 8. Set nanoseconds to remainder(nanoseconds, 1000).
  940. nanoseconds = fmod(nanoseconds, 1000);
  941. // 9. Set milliseconds to milliseconds + the integral part of microseconds / 1000.
  942. milliseconds += trunc(microseconds / 1000);
  943. // 10. Set microseconds to remainder(microseconds, 1000).
  944. microseconds = fmod(microseconds, 1000);
  945. // 11. Set seconds to seconds + the integral part of milliseconds / 1000.
  946. seconds += trunc(milliseconds / 1000);
  947. // 12. Set milliseconds to remainder(milliseconds, 1000).
  948. milliseconds = fmod(milliseconds, 1000);
  949. // 13. Let datePart be "".
  950. StringBuilder date_part;
  951. // 14. If years is not 0, then
  952. if (years != 0) {
  953. // a. Set datePart to the string concatenation of abs(years) formatted as a decimal number and the code unit 0x0059 (LATIN CAPITAL LETTER Y).
  954. date_part.appendff("{}", fabs(years));
  955. date_part.append('Y');
  956. }
  957. // 15. If months is not 0, then
  958. if (months != 0) {
  959. // 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).
  960. date_part.appendff("{}", fabs(months));
  961. date_part.append('M');
  962. }
  963. // 16. If weeks is not 0, then
  964. if (weeks != 0) {
  965. // 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).
  966. date_part.appendff("{}", fabs(weeks));
  967. date_part.append('W');
  968. }
  969. // 17. If days is not 0, then
  970. if (days != 0) {
  971. // 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).
  972. date_part.appendff("{}", fabs(days));
  973. date_part.append('D');
  974. }
  975. // 18. Let timePart be "".
  976. StringBuilder time_part;
  977. // 19. If hours is not 0, then
  978. if (hours != 0) {
  979. // a. Set timePart to the string concatenation of abs(hours) formatted as a decimal number and the code unit 0x0048 (LATIN CAPITAL LETTER H).
  980. time_part.appendff("{}", fabs(hours));
  981. time_part.append('H');
  982. }
  983. // 20. If minutes is not 0, then
  984. if (minutes != 0) {
  985. // 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).
  986. time_part.appendff("{}", fabs(minutes));
  987. time_part.append('M');
  988. }
  989. // 21. If any of seconds, milliseconds, microseconds, and nanoseconds are not 0; or years, months, weeks, days, hours, and minutes are all 0, then
  990. if ((seconds != 0 || milliseconds != 0 || microseconds != 0 || nanoseconds != 0) || (years == 0 && months == 0 && weeks == 0 && days == 0 && hours == 0 && minutes == 0)) {
  991. // a. Let fraction be abs(milliseconds) × 10^6 + abs(microseconds) × 10^3 + abs(nanoseconds).
  992. auto fraction = fabs(milliseconds) * 1'000'000 + fabs(microseconds) * 1'000 + fabs(nanoseconds);
  993. // b. Let decimalPart be fraction formatted as a nine-digit decimal number, padded to the left with zeroes if necessary.
  994. // 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.
  995. auto decimal_part = String::formatted("{:09}", (u64)fraction);
  996. // c. If precision is "auto", then
  997. if (precision.has<StringView>() && precision.get<StringView>() == "auto"sv) {
  998. // i. Set decimalPart to the longest possible substring of decimalPart starting at position 0 and not ending with the code unit 0x0030 (DIGIT ZERO).
  999. // NOTE: trim() would keep the left-most 0.
  1000. while (decimal_part.ends_with('0'))
  1001. decimal_part = decimal_part.substring(0, decimal_part.length() - 1);
  1002. }
  1003. // d. Else if precision = 0, then
  1004. else if (precision.get<u8>() == 0) {
  1005. // i. Set decimalPart to "".
  1006. decimal_part = String::empty();
  1007. }
  1008. // e. Else,
  1009. else {
  1010. // i. Set decimalPart to the substring of decimalPart from 0 to precision.
  1011. decimal_part = decimal_part.substring(0, precision.get<u8>());
  1012. }
  1013. // f. Let secondsPart be abs(seconds) formatted as a decimal number.
  1014. StringBuilder seconds_part;
  1015. seconds_part.appendff("{}", fabs(seconds));
  1016. // g. If decimalPart is not "", then
  1017. if (!decimal_part.is_empty()) {
  1018. // i. Set secondsPart to the string-concatenation of secondsPart, the code unit 0x002E (FULL STOP), and decimalPart.
  1019. seconds_part.append('.');
  1020. seconds_part.append(decimal_part);
  1021. }
  1022. // h. Set timePart to the string concatenation of timePart, secondsPart, and the code unit 0x0053 (LATIN CAPITAL LETTER S).
  1023. time_part.append(seconds_part.string_view());
  1024. time_part.append('S');
  1025. }
  1026. // 22. Let signPart be the code unit 0x002D (HYPHEN-MINUS) if sign < 0, and otherwise the empty String.
  1027. auto sign_part = sign < 0 ? "-"sv : ""sv;
  1028. // 23. Let result be the string concatenation of signPart, the code unit 0x0050 (LATIN CAPITAL LETTER P) and datePart.
  1029. StringBuilder result;
  1030. result.append(sign_part);
  1031. result.append('P');
  1032. result.append(date_part.string_view());
  1033. // 24. If timePart is not "", then
  1034. if (!time_part.is_empty()) {
  1035. // a. Set result to the string concatenation of result, the code unit 0x0054 (LATIN CAPITAL LETTER T), and timePart.
  1036. result.append('T');
  1037. result.append(time_part.string_view());
  1038. }
  1039. // 25. Return result.
  1040. return result.to_string();
  1041. }
  1042. }