Duration.cpp 68 KB

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