/
calendar.ts
2570 lines (2477 loc) · 109 KB
/
calendar.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { DEBUG } from './debug';
import * as ES from './ecmascript';
import { GetIntrinsic, MakeIntrinsicClass, DefineIntrinsic } from './intrinsicclass';
import {
CALENDAR_ID,
ISO_YEAR,
ISO_MONTH,
ISO_DAY,
YEARS,
MONTHS,
WEEKS,
DAYS,
HOURS,
MINUTES,
SECONDS,
MILLISECONDS,
MICROSECONDS,
NANOSECONDS,
CreateSlots,
GetSlot,
HasSlot,
SetSlot
} from './slots';
import type { Temporal } from '..';
import type {
BuiltinCalendarId,
CalendarParams as Params,
CalendarReturn as Return,
AnyTemporalKey,
CalendarSlot
} from './internaltypes';
const ArrayIncludes = Array.prototype.includes;
const ArrayPrototypePush = Array.prototype.push;
const IntlDateTimeFormat = globalThis.Intl.DateTimeFormat;
const ArraySort = Array.prototype.sort;
const MathAbs = Math.abs;
const MathFloor = Math.floor;
const ObjectCreate = Object.create;
const ObjectEntries = Object.entries;
const OriginalSet = Set;
const ReflectOwnKeys = Reflect.ownKeys;
const SetPrototypeAdd = Set.prototype.add;
const SetPrototypeValues = Set.prototype.values;
/**
* Shape of internal implementation of each built-in calendar. Note that
* parameter types are simpler than CalendarProtocol because the `Calendar`
* class performs validation and parameter normalization before handing control
* over to CalendarImpl.
*
* There are two instances of this interface: one for the ISO calendar and
* another that handles logic that's the same across all non-ISO calendars. The
* latter is cloned for each non-ISO calendar at the end of this file.
*/
interface CalendarImpl {
year(date: Temporal.PlainDate | Temporal.PlainYearMonth): number;
month(date: Temporal.PlainDate | Temporal.PlainYearMonth | Temporal.PlainMonthDay): number;
monthCode(date: Temporal.PlainDate | Temporal.PlainYearMonth | Temporal.PlainMonthDay): string;
day(date: Temporal.PlainDate | Temporal.PlainMonthDay): number;
era(date: Temporal.PlainDate | Temporal.PlainYearMonth): string | undefined;
eraYear(date: Temporal.PlainDate | Temporal.PlainYearMonth): number | undefined;
dayOfWeek(date: Temporal.PlainDate): number;
dayOfYear(date: Temporal.PlainDate): number;
weekOfYear(date: Temporal.PlainDate): number;
yearOfWeek(date: Temporal.PlainDate): number;
daysInWeek(date: Temporal.PlainDate): number;
daysInMonth(date: Temporal.PlainDate | Temporal.PlainYearMonth): number;
daysInYear(date: Temporal.PlainDate | Temporal.PlainYearMonth): number;
monthsInYear(date: Temporal.PlainDate | Temporal.PlainYearMonth): number;
inLeapYear(date: Temporal.PlainDate | Temporal.PlainYearMonth): boolean;
dateFromFields(
fields: Params['dateFromFields'][0],
options: NonNullable<Params['dateFromFields'][1]>,
calendar: string
): Temporal.PlainDate;
yearMonthFromFields(
fields: Params['yearMonthFromFields'][0],
options: NonNullable<Params['yearMonthFromFields'][1]>,
calendar: string
): Temporal.PlainYearMonth;
monthDayFromFields(
fields: Params['monthDayFromFields'][0],
options: NonNullable<Params['monthDayFromFields'][1]>,
calendar: string
): Temporal.PlainMonthDay;
dateAdd(
date: Temporal.PlainDate,
years: number,
months: number,
weeks: number,
days: number,
overflow: Overflow,
calendar: string
): Temporal.PlainDate;
dateUntil(
one: Temporal.PlainDate,
two: Temporal.PlainDate,
largestUnit: 'year' | 'month' | 'week' | 'day'
): { years: number; months: number; weeks: number; days: number };
fields(fields: string[]): string[];
fieldKeysToIgnore(keys: string[]): string[];
}
type CalendarImplementations = {
[k in BuiltinCalendarId]: CalendarImpl;
};
/**
* Implementations for each calendar.
* Registration for each of these calendars happens throughout this file. The ISO and non-ISO calendars are registered
* separately - look for 'iso8601' for the ISO calendar registration, and all non-ISO calendar registrations happens
* at the bottom of the file.
*/
const impl: CalendarImplementations = {} as unknown as CalendarImplementations;
/**
* Thin wrapper around the implementation of each built-in calendar. This
* class's methods follow a similar pattern:
* 1. Validate parameters
* 2. Fill in default options (for methods where options are present)
* 3. Simplify and/or normalize parameters. For example, some methods accept
* PlainDate, PlainDateTime, ZonedDateTime, etc. and these are normalized to
* PlainDate.
* 4. Look up the ID of the built-in calendar
* 5. Fetch the implementation object for that ID.
* 6. Call the corresponding method in the implementation object.
*/
export class Calendar implements Temporal.Calendar {
constructor(idParam: Params['constructor'][0]) {
// Note: if the argument is not passed, IsBuiltinCalendar("undefined") will fail. This check
// exists only to improve the error message.
if (arguments.length < 1) {
throw new RangeError('missing argument: id is required');
}
const id = ES.ToString(idParam);
if (!ES.IsBuiltinCalendar(id)) throw new RangeError(`invalid calendar identifier ${id}`);
CreateSlots(this);
SetSlot(this, CALENDAR_ID, ES.ASCIILowercase(id));
if (DEBUG) {
Object.defineProperty(this, '_repr_', {
value: `${this[Symbol.toStringTag]} <${id}>`,
writable: false,
enumerable: false,
configurable: false
});
}
}
get id(): Return['id'] {
if (!ES.IsTemporalCalendar(this)) throw new TypeError('invalid receiver');
return GetSlot(this, CALENDAR_ID);
}
dateFromFields(
fields: Params['dateFromFields'][0],
optionsParam: Params['dateFromFields'][1] = undefined
): Return['dateFromFields'] {
if (!ES.IsTemporalCalendar(this)) throw new TypeError('invalid receiver');
if (!ES.IsObject(fields)) throw new TypeError('invalid fields');
const options = ES.GetOptionsObject(optionsParam);
const id = GetSlot(this, CALENDAR_ID);
return impl[id].dateFromFields(fields, options, id);
}
yearMonthFromFields(
fields: Params['yearMonthFromFields'][0],
optionsParam: Params['yearMonthFromFields'][1] = undefined
): Return['yearMonthFromFields'] {
if (!ES.IsTemporalCalendar(this)) throw new TypeError('invalid receiver');
if (!ES.IsObject(fields)) throw new TypeError('invalid fields');
const options = ES.GetOptionsObject(optionsParam);
const id = GetSlot(this, CALENDAR_ID);
return impl[id].yearMonthFromFields(fields, options, id);
}
monthDayFromFields(
fields: Params['monthDayFromFields'][0],
optionsParam: Params['monthDayFromFields'][1] = undefined
): Return['monthDayFromFields'] {
if (!ES.IsTemporalCalendar(this)) throw new TypeError('invalid receiver');
if (!ES.IsObject(fields)) throw new TypeError('invalid fields');
const options = ES.GetOptionsObject(optionsParam);
const id = GetSlot(this, CALENDAR_ID);
return impl[id].monthDayFromFields(fields, options, id);
}
fields(fields: Params['fields'][0]): Return['fields'] {
if (!ES.IsTemporalCalendar(this)) throw new TypeError('invalid receiver');
const fieldsArray = [] as string[];
const allowed = new Set([
'year',
'month',
'monthCode',
'day',
'hour',
'minute',
'second',
'millisecond',
'microsecond',
'nanosecond'
]);
for (const name of fields) {
if (typeof name !== 'string') throw new TypeError('invalid fields');
if (!allowed.has(name)) throw new RangeError(`invalid field name ${name}`);
allowed.delete(name);
ArrayPrototypePush.call(fieldsArray, name);
}
return impl[GetSlot(this, CALENDAR_ID)].fields(fieldsArray);
}
mergeFields(fields: Params['mergeFields'][0], additionalFields: Params['mergeFields'][1]): Return['mergeFields'] {
if (!ES.IsTemporalCalendar(this)) throw new TypeError('invalid receiver');
const fieldsCopy = ES.SnapshotOwnProperties(fields, null, [], [undefined]);
const additionalFieldsCopy = ES.SnapshotOwnProperties(additionalFields, null, [], [undefined]);
const additionalKeys = ReflectOwnKeys(additionalFieldsCopy) as (keyof typeof additionalFields)[];
const overriddenKeys = impl[GetSlot(this, CALENDAR_ID)].fieldKeysToIgnore(additionalKeys);
const merged = ObjectCreate(null);
const fieldsKeys = ReflectOwnKeys(fieldsCopy);
ES.uncheckedAssertNarrowedType<string[]>(fieldsKeys, 'Reflect.ownKeys does not respect the type of its input');
for (const key of fieldsKeys) {
let propValue = undefined;
if (ES.Call(ArrayIncludes, overriddenKeys, [key])) propValue = additionalFieldsCopy[key];
else propValue = fieldsCopy[key];
if (propValue !== undefined) merged[key] = propValue;
}
ES.CopyDataProperties(merged, additionalFieldsCopy, []);
return merged;
}
dateAdd(
dateParam: Params['dateAdd'][0],
durationParam: Params['dateAdd'][1],
optionsParam: Params['dateAdd'][2] = undefined
): Return['dateAdd'] {
if (!ES.IsTemporalCalendar(this)) throw new TypeError('invalid receiver');
const date = ES.ToTemporalDate(dateParam);
const duration = ES.ToTemporalDuration(durationParam);
const options = ES.GetOptionsObject(optionsParam);
const overflow = ES.ToTemporalOverflow(options);
const { days } = ES.BalanceDuration(
GetSlot(duration, DAYS),
GetSlot(duration, HOURS),
GetSlot(duration, MINUTES),
GetSlot(duration, SECONDS),
GetSlot(duration, MILLISECONDS),
GetSlot(duration, MICROSECONDS),
GetSlot(duration, NANOSECONDS),
'day'
);
const id = GetSlot(this, CALENDAR_ID);
return impl[id].dateAdd(
date,
GetSlot(duration, YEARS),
GetSlot(duration, MONTHS),
GetSlot(duration, WEEKS),
days,
overflow,
id
);
}
dateUntil(
oneParam: Params['dateUntil'][0],
twoParam: Params['dateUntil'][1],
optionsParam: Params['dateUntil'][2] = undefined
): Return['dateUntil'] {
if (!ES.IsTemporalCalendar(this)) throw new TypeError('invalid receiver');
const one = ES.ToTemporalDate(oneParam);
const two = ES.ToTemporalDate(twoParam);
const options = ES.GetOptionsObject(optionsParam);
let largestUnit = ES.GetTemporalUnit(options, 'largestUnit', 'date', 'auto');
if (largestUnit === 'auto') largestUnit = 'day';
const { years, months, weeks, days } = impl[GetSlot(this, CALENDAR_ID)].dateUntil(one, two, largestUnit);
const Duration = GetIntrinsic('%Temporal.Duration%');
return new Duration(years, months, weeks, days, 0, 0, 0, 0, 0, 0);
}
year(dateParam: Params['year'][0]): Return['year'] {
let date = dateParam;
if (!ES.IsTemporalCalendar(this)) throw new TypeError('invalid receiver');
if (!ES.IsTemporalYearMonth(date)) date = ES.ToTemporalDate(date);
return impl[GetSlot(this, CALENDAR_ID)].year(date as Temporal.PlainDate | Temporal.PlainYearMonth);
}
month(dateParam: Params['month'][0]): Return['month'] {
let date = dateParam;
if (!ES.IsTemporalCalendar(this)) throw new TypeError('invalid receiver');
if (ES.IsTemporalMonthDay(date)) throw new TypeError('use monthCode on PlainMonthDay instead');
if (!ES.IsTemporalYearMonth(date)) date = ES.ToTemporalDate(date);
return impl[GetSlot(this, CALENDAR_ID)].month(date as Temporal.PlainDate | Temporal.PlainYearMonth);
}
monthCode(dateParam: Params['monthCode'][0]): Return['monthCode'] {
let date = dateParam;
if (!ES.IsTemporalCalendar(this)) throw new TypeError('invalid receiver');
if (!ES.IsTemporalYearMonth(date) && !ES.IsTemporalMonthDay(date)) date = ES.ToTemporalDate(date);
return impl[GetSlot(this, CALENDAR_ID)].monthCode(
date as Temporal.PlainDate | Temporal.PlainMonthDay | Temporal.PlainYearMonth
);
}
day(dateParam: Params['day'][0]): Return['day'] {
let date = dateParam;
if (!ES.IsTemporalCalendar(this)) throw new TypeError('invalid receiver');
if (!ES.IsTemporalMonthDay(date)) date = ES.ToTemporalDate(date);
return impl[GetSlot(this, CALENDAR_ID)].day(date as Temporal.PlainDate | Temporal.PlainMonthDay);
}
era(dateParam: Params['era'][0]): Return['era'] {
let date = dateParam;
if (!ES.IsTemporalCalendar(this)) throw new TypeError('invalid receiver');
if (!ES.IsTemporalYearMonth(date)) date = ES.ToTemporalDate(date);
return impl[GetSlot(this, CALENDAR_ID)].era(date as Temporal.PlainDate | Temporal.PlainYearMonth);
}
eraYear(dateParam: Params['eraYear'][0]): Return['eraYear'] {
let date = dateParam;
if (!ES.IsTemporalCalendar(this)) throw new TypeError('invalid receiver');
if (!ES.IsTemporalYearMonth(date)) date = ES.ToTemporalDate(date);
return impl[GetSlot(this, CALENDAR_ID)].eraYear(date as Temporal.PlainDate | Temporal.PlainYearMonth);
}
dayOfWeek(dateParam: Params['dayOfWeek'][0]): Return['dayOfWeek'] {
if (!ES.IsTemporalCalendar(this)) throw new TypeError('invalid receiver');
const date = ES.ToTemporalDate(dateParam);
return impl[GetSlot(this, CALENDAR_ID)].dayOfWeek(date);
}
dayOfYear(dateParam: Params['dayOfYear'][0]): Return['dayOfYear'] {
if (!ES.IsTemporalCalendar(this)) throw new TypeError('invalid receiver');
const date = ES.ToTemporalDate(dateParam);
return impl[GetSlot(this, CALENDAR_ID)].dayOfYear(date);
}
weekOfYear(dateParam: Params['weekOfYear'][0]): Return['weekOfYear'] {
if (!ES.IsTemporalCalendar(this)) throw new TypeError('invalid receiver');
const date = ES.ToTemporalDate(dateParam);
return impl[GetSlot(this, CALENDAR_ID)].weekOfYear(date);
}
yearOfWeek(dateParam: Params['yearOfWeek'][0]): Return['yearOfWeek'] {
if (!ES.IsTemporalCalendar(this)) throw new TypeError('invalid receiver');
const date = ES.ToTemporalDate(dateParam);
return impl[GetSlot(this, CALENDAR_ID)].yearOfWeek(date);
}
daysInWeek(dateParam: Params['daysInWeek'][0]): Return['daysInWeek'] {
if (!ES.IsTemporalCalendar(this)) throw new TypeError('invalid receiver');
const date = ES.ToTemporalDate(dateParam);
return impl[GetSlot(this, CALENDAR_ID)].daysInWeek(date);
}
daysInMonth(dateParam: Params['daysInMonth'][0]): Return['daysInMonth'] {
let date = dateParam;
if (!ES.IsTemporalCalendar(this)) throw new TypeError('invalid receiver');
if (!ES.IsTemporalYearMonth(date)) date = ES.ToTemporalDate(date);
return impl[GetSlot(this, CALENDAR_ID)].daysInMonth(date as Temporal.PlainDate | Temporal.PlainYearMonth);
}
daysInYear(dateParam: Params['daysInYear'][0]): Return['daysInYear'] {
let date = dateParam;
if (!ES.IsTemporalCalendar(this)) throw new TypeError('invalid receiver');
if (!ES.IsTemporalYearMonth(date)) date = ES.ToTemporalDate(date);
return impl[GetSlot(this, CALENDAR_ID)].daysInYear(date as Temporal.PlainDate | Temporal.PlainYearMonth);
}
monthsInYear(dateParam: Params['monthsInYear'][0]): Return['monthsInYear'] {
let date = dateParam;
if (!ES.IsTemporalCalendar(this)) throw new TypeError('invalid receiver');
if (!ES.IsTemporalYearMonth(date)) date = ES.ToTemporalDate(date);
return impl[GetSlot(this, CALENDAR_ID)].monthsInYear(date as Temporal.PlainDate | Temporal.PlainYearMonth);
}
inLeapYear(dateParam: Params['inLeapYear'][0]): Return['inLeapYear'] {
let date = dateParam;
if (!ES.IsTemporalCalendar(this)) throw new TypeError('invalid receiver');
if (!ES.IsTemporalYearMonth(date)) date = ES.ToTemporalDate(date);
return impl[GetSlot(this, CALENDAR_ID)].inLeapYear(date as Temporal.PlainDate | Temporal.PlainYearMonth);
}
toString(): string {
if (!ES.IsTemporalCalendar(this)) throw new TypeError('invalid receiver');
return GetSlot(this, CALENDAR_ID);
}
toJSON(): Return['toJSON'] {
if (!ES.IsTemporalCalendar(this)) throw new TypeError('invalid receiver');
return GetSlot(this, CALENDAR_ID);
}
static from(item: Params['from'][0]): Return['from'] {
const calendarSlotValue = ES.ToTemporalCalendarSlotValue(item);
return ES.ToTemporalCalendarObject(calendarSlotValue);
}
[Symbol.toStringTag]!: 'Temporal.Calendar';
}
MakeIntrinsicClass(Calendar, 'Temporal.Calendar');
DefineIntrinsic('Temporal.Calendar.from', Calendar.from);
DefineIntrinsic('Temporal.Calendar.prototype.dateAdd', Calendar.prototype.dateAdd);
DefineIntrinsic('Temporal.Calendar.prototype.dateFromFields', Calendar.prototype.dateFromFields);
DefineIntrinsic('Temporal.Calendar.prototype.dateUntil', Calendar.prototype.dateUntil);
DefineIntrinsic('Temporal.Calendar.prototype.day', Calendar.prototype.day);
DefineIntrinsic('Temporal.Calendar.prototype.dayOfWeek', Calendar.prototype.dayOfWeek);
DefineIntrinsic('Temporal.Calendar.prototype.dayOfYear', Calendar.prototype.dayOfYear);
DefineIntrinsic('Temporal.Calendar.prototype.daysInMonth', Calendar.prototype.daysInMonth);
DefineIntrinsic('Temporal.Calendar.prototype.daysInWeek', Calendar.prototype.daysInWeek);
DefineIntrinsic('Temporal.Calendar.prototype.daysInYear', Calendar.prototype.daysInYear);
DefineIntrinsic('Temporal.Calendar.prototype.era', Calendar.prototype.era);
DefineIntrinsic('Temporal.Calendar.prototype.eraYear', Calendar.prototype.eraYear);
DefineIntrinsic('Temporal.Calendar.prototype.fields', Calendar.prototype.fields);
DefineIntrinsic('Temporal.Calendar.prototype.inLeapYear', Calendar.prototype.inLeapYear);
DefineIntrinsic('Temporal.Calendar.prototype.mergeFields', Calendar.prototype.mergeFields);
DefineIntrinsic('Temporal.Calendar.prototype.month', Calendar.prototype.month);
DefineIntrinsic('Temporal.Calendar.prototype.monthCode', Calendar.prototype.monthCode);
DefineIntrinsic('Temporal.Calendar.prototype.monthDayFromFields', Calendar.prototype.monthDayFromFields);
DefineIntrinsic('Temporal.Calendar.prototype.monthsInYear', Calendar.prototype.monthsInYear);
DefineIntrinsic('Temporal.Calendar.prototype.weekOfYear', Calendar.prototype.weekOfYear);
DefineIntrinsic('Temporal.Calendar.prototype.year', Calendar.prototype.year);
DefineIntrinsic('Temporal.Calendar.prototype.yearMonthFromFields', Calendar.prototype.yearMonthFromFields);
DefineIntrinsic('Temporal.Calendar.prototype.yearOfWeek', Calendar.prototype.yearOfWeek);
/**
* Implementation for the ISO 8601 calendar. This is the only calendar that's
* guaranteed to be supported by all ECMAScript implementations, including those
* without Intl (ECMA-402) support.
*/
impl['iso8601'] = {
dateFromFields(fieldsParam, options, calendarSlotValue) {
let fields = ES.PrepareTemporalFields(fieldsParam, ['day', 'month', 'monthCode', 'year'], ['year', 'day']);
const overflow = ES.ToTemporalOverflow(options);
fields = resolveNonLunisolarMonth(fields);
let { year, month, day } = fields;
({ year, month, day } = ES.RegulateISODate(year, month, day, overflow));
return ES.CreateTemporalDate(year, month, day, calendarSlotValue);
},
yearMonthFromFields(fieldsParam, options, calendarSlotValue) {
let fields = ES.PrepareTemporalFields(fieldsParam, ['month', 'monthCode', 'year'], ['year']);
const overflow = ES.ToTemporalOverflow(options);
fields = resolveNonLunisolarMonth(fields);
let { year, month } = fields;
({ year, month } = ES.RegulateISOYearMonth(year, month, overflow));
return ES.CreateTemporalYearMonth(year, month, calendarSlotValue, /* referenceISODay = */ 1);
},
monthDayFromFields(fieldsParam, options, calendarSlotValue) {
let fields = ES.PrepareTemporalFields(fieldsParam, ['day', 'month', 'monthCode', 'year'], ['day']);
const overflow = ES.ToTemporalOverflow(options);
if (fields.month !== undefined && fields.year === undefined && fields.monthCode === undefined) {
throw new TypeError('either year or monthCode required with month');
}
const useYear = fields.monthCode === undefined;
const referenceISOYear = 1972;
fields = resolveNonLunisolarMonth(fields);
let { month, day, year } = fields;
({ month, day } = ES.RegulateISODate(useYear ? year : referenceISOYear, month, day, overflow));
return ES.CreateTemporalMonthDay(month, day, calendarSlotValue, referenceISOYear);
},
fields(fields) {
return fields;
},
fieldKeysToIgnore(keys) {
const result = new OriginalSet();
for (let ix = 0; ix < keys.length; ix++) {
const key = keys[ix];
ES.Call(SetPrototypeAdd, result, [key]);
if (key === 'month') {
ES.Call(SetPrototypeAdd, result, ['monthCode']);
} else if (key === 'monthCode') {
ES.Call(SetPrototypeAdd, result, ['month']);
}
}
return [...ES.Call(SetPrototypeValues, result, [])];
},
dateAdd(date, years, months, weeks, days, overflow, calendarSlotValue) {
let year = GetSlot(date, ISO_YEAR);
let month = GetSlot(date, ISO_MONTH);
let day = GetSlot(date, ISO_DAY);
({ year, month, day } = ES.AddISODate(year, month, day, years, months, weeks, days, overflow));
return ES.CreateTemporalDate(year, month, day, calendarSlotValue);
},
dateUntil(one, two, largestUnit) {
return ES.DifferenceISODate(
GetSlot(one, ISO_YEAR),
GetSlot(one, ISO_MONTH),
GetSlot(one, ISO_DAY),
GetSlot(two, ISO_YEAR),
GetSlot(two, ISO_MONTH),
GetSlot(two, ISO_DAY),
largestUnit
);
},
year(date) {
return GetSlot(date, ISO_YEAR);
},
era() {
return undefined;
},
eraYear() {
return undefined;
},
month(date) {
return GetSlot(date, ISO_MONTH);
},
monthCode(date) {
return buildMonthCode(GetSlot(date, ISO_MONTH));
},
day(date) {
return GetSlot(date, ISO_DAY);
},
dayOfWeek(date) {
return ES.DayOfWeek(GetSlot(date, ISO_YEAR), GetSlot(date, ISO_MONTH), GetSlot(date, ISO_DAY));
},
dayOfYear(date) {
return ES.DayOfYear(GetSlot(date, ISO_YEAR), GetSlot(date, ISO_MONTH), GetSlot(date, ISO_DAY));
},
weekOfYear(date) {
return ES.WeekOfYear(GetSlot(date, ISO_YEAR), GetSlot(date, ISO_MONTH), GetSlot(date, ISO_DAY)).week;
},
yearOfWeek(date) {
return ES.WeekOfYear(GetSlot(date, ISO_YEAR), GetSlot(date, ISO_MONTH), GetSlot(date, ISO_DAY)).year;
},
daysInWeek() {
return 7;
},
daysInMonth(date) {
return ES.ISODaysInMonth(GetSlot(date, ISO_YEAR), GetSlot(date, ISO_MONTH));
},
daysInYear(dateParam) {
let date = dateParam;
if (!HasSlot(date, ISO_YEAR)) date = ES.ToTemporalDate(date);
return ES.LeapYear(GetSlot(date, ISO_YEAR)) ? 366 : 365;
},
monthsInYear() {
return 12;
},
inLeapYear(dateParam) {
let date = dateParam;
if (!HasSlot(date, ISO_YEAR)) date = ES.ToTemporalDate(date);
return ES.LeapYear(GetSlot(date, ISO_YEAR));
}
};
// Note: Built-in calendars other than iso8601 are not part of the Temporal
// proposal for ECMA-262. These calendars will be standardized as part of
// ECMA-402. Code below here includes an implementation of these calendars to
// validate the Temporal API and to get feedback. However, native non-ISO
// calendar behavior is at least somewhat implementation-defined, so may not
// match this polyfill's output exactly.
//
// Some ES implementations don't include ECMA-402. For this reason, it's helpful
// to ensure a clean separation between the ISO calendar implementation which is
// a part of ECMA-262 and the non-ISO calendar implementation which requires
// ECMA-402.
//
// To ensure this separation, the implementation is split. A `CalendarImpl`
// interface defines the common operations between both ISO and non-ISO
// calendars.
/**
* This type is passed through from Calendar#dateFromFields().
* `monthExtra` is additional information used internally to identify lunisolar leap months.
*/
type CalendarDateFields = Params['dateFromFields'][0] & { monthExtra?: string };
/**
* This is a "fully populated" calendar date record. It's only lacking
* `era`/`eraYear` (which may not be present in all calendars) and `monthExtra`
* which is only used in some cases.
*/
type FullCalendarDate = {
era?: string;
eraYear?: number;
year: number;
month: number;
monthCode: string;
day: number;
monthExtra?: string;
};
// The types below are various subsets of calendar dates
type CalendarYMD = { year: number; month: number; day: number };
type CalendarYM = { year: number; month: number };
type CalendarYearOnly = { year: number };
type EraAndEraYear = { era: string; eraYear: number };
/** Record representing YMD of an ISO calendar date */
type IsoYMD = { year: number; month: number; day: number };
type Overflow = NonNullable<Temporal.AssignmentOptions['overflow']>;
function monthCodeNumberPart(monthCode: string) {
if (!monthCode.startsWith('M')) {
throw new RangeError(`Invalid month code: ${monthCode}. Month codes must start with M.`);
}
const month = +monthCode.slice(1);
if (isNaN(month)) throw new RangeError(`Invalid month code: ${monthCode}`);
return month;
}
function buildMonthCode(month: number | string, leap = false) {
return `M${month.toString().padStart(2, '0')}${leap ? 'L' : ''}`;
}
/**
* Safely merge a month, monthCode pair into an integer month.
* If both are present, make sure they match.
* This logic doesn't work for lunisolar calendars!
* */
function resolveNonLunisolarMonth<T extends { monthCode?: string; month?: number }>(
calendarDate: T,
overflow: Overflow | undefined = undefined,
monthsPerYear = 12
) {
let { month, monthCode } = calendarDate;
if (monthCode === undefined) {
if (month === undefined) throw new TypeError('Either month or monthCode are required');
// The ISO calendar uses the default (undefined) value because it does
// constrain/reject after this method returns. Non-ISO calendars, however,
// rely on this function to constrain/reject out-of-range `month` values.
if (overflow === 'reject') ES.RejectToRange(month, 1, monthsPerYear);
if (overflow === 'constrain') month = ES.ConstrainToRange(month, 1, monthsPerYear);
monthCode = buildMonthCode(month);
} else {
const numberPart = monthCodeNumberPart(monthCode);
if (month !== undefined && month !== numberPart) {
throw new RangeError(`monthCode ${monthCode} and month ${month} must match if both are present`);
}
if (monthCode !== buildMonthCode(numberPart)) {
throw new RangeError(`Invalid month code: ${monthCode}`);
}
month = numberPart;
if (month < 1 || month > monthsPerYear) throw new RangeError(`Invalid monthCode: ${monthCode}`);
}
return { ...calendarDate, month, monthCode };
}
type CachedTypes = Temporal.PlainYearMonth | Temporal.PlainDate | Temporal.PlainMonthDay;
/**
* This prototype implementation of non-ISO calendars makes many repeated calls
* to Intl APIs which may be slow (e.g. >0.2ms). This trivial cache will speed
* up these repeat accesses. Each cache instance is associated (via a WeakMap)
* to a specific Temporal object, which speeds up multiple calendar calls on the
* same Temporal object instance. No invalidation or pruning is necessary
* because each object's cache is thrown away when the object is GC-ed.
*/
class OneObjectCache {
map = new Map();
calls = 0;
now: number;
hits = 0;
misses = 0;
constructor(cacheToClone?: OneObjectCache) {
this.now = globalThis.performance ? globalThis.performance.now() : Date.now();
if (cacheToClone !== undefined) {
let i = 0;
for (const entry of cacheToClone.map.entries()) {
if (++i > OneObjectCache.MAX_CACHE_ENTRIES) break;
this.map.set(...entry);
}
}
}
get(key: string) {
const result = this.map.get(key);
if (result) {
this.hits++;
this.report();
}
this.calls++;
return result;
}
set(key: string, value: unknown) {
this.map.set(key, value);
this.misses++;
this.report();
}
report() {
/*
if (this.calls === 0) return;
const ms = (globalThis.performance ? globalThis.performance.now() : Date.now()) - this.now;
const hitRate = ((100 * this.hits) / this.calls).toFixed(0);
console.log(`${this.calls} calls in ${ms.toFixed(2)}ms. Hits: ${this.hits} (${hitRate}%). Misses: ${this.misses}.`);
*/
}
setObject(obj: CachedTypes) {
if (OneObjectCache.objectMap.get(obj)) throw new RangeError('object already cached');
OneObjectCache.objectMap.set(obj, this);
this.report();
}
static objectMap = new WeakMap();
static MAX_CACHE_ENTRIES = 1000;
/**
* Returns a WeakMap-backed cache that's used to store expensive results
* that are associated with a particular Temporal object instance.
*
* @param obj - object to associate with the cache
*/
static getCacheForObject(obj: CachedTypes) {
let cache = OneObjectCache.objectMap.get(obj);
if (!cache) {
cache = new OneObjectCache();
OneObjectCache.objectMap.set(obj, cache);
}
return cache;
}
}
function toUtcIsoDateString({ isoYear, isoMonth, isoDay }: { isoYear: number; isoMonth: number; isoDay: number }) {
const yearString = ES.ISOYearString(isoYear);
const monthString = ES.ISODateTimePartString(isoMonth);
const dayString = ES.ISODateTimePartString(isoDay);
return `${yearString}-${monthString}-${dayString}T00:00Z`;
}
function simpleDateDiff(one: CalendarYMD, two: CalendarYMD) {
return {
years: one.year - two.year,
months: one.month - two.month,
days: one.day - two.day
};
}
/**
* Implementation helper that's common to all non-ISO calendars
*/
abstract class HelperBase {
abstract id: BuiltinCalendarId;
abstract monthsInYear(calendarDate: CalendarYearOnly, cache?: OneObjectCache): number;
abstract maximumMonthLength(calendarDate?: CalendarYM): number;
abstract minimumMonthLength(calendarDate?: CalendarYM): number;
abstract estimateIsoDate(calendarDate: CalendarYMD): IsoYMD;
abstract inLeapYear(calendarDate: CalendarYearOnly, cache?: OneObjectCache): boolean;
abstract calendarType: 'solar' | 'lunar' | 'lunisolar';
reviseIntlEra?<T extends Partial<EraAndEraYear>>(calendarDate: T, isoDate: IsoYMD): T;
constantEra?: string;
checkIcuBugs?(isoDate: IsoYMD): void;
private formatter?: globalThis.Intl.DateTimeFormat;
getFormatter() {
// `new Intl.DateTimeFormat()` is amazingly slow and chews up RAM. Per
// https://bugs.chromium.org/p/v8/issues/detail?id=6528#c4, we cache one
// DateTimeFormat instance per calendar. Caching is lazy so we only pay for
// calendars that are used. Note that the nonIsoHelperBase object is spread
// into each each calendar's implementation before any cache is created, so
// each calendar gets its own separate cached formatter.
if (typeof this.formatter === 'undefined') {
this.formatter = new IntlDateTimeFormat(`en-US-u-ca-${this.id}`, {
day: 'numeric',
month: 'numeric',
year: 'numeric',
era: 'short',
timeZone: 'UTC'
});
}
return this.formatter;
}
isoToCalendarDate(isoDate: IsoYMD, cache: OneObjectCache): FullCalendarDate {
const { year: isoYear, month: isoMonth, day: isoDay } = isoDate;
const key = JSON.stringify({ func: 'isoToCalendarDate', isoYear, isoMonth, isoDay, id: this.id });
const cached = cache.get(key);
if (cached) return cached;
const dateTimeFormat = this.getFormatter();
let parts, isoString;
try {
isoString = toUtcIsoDateString({ isoYear, isoMonth, isoDay });
parts = dateTimeFormat.formatToParts(new Date(isoString));
} catch (e: unknown) {
throw new RangeError(`Invalid ISO date: ${JSON.stringify({ isoYear, isoMonth, isoDay })}`);
}
const result: Partial<FullCalendarDate> = {};
for (let { type, value } of parts) {
if (type === 'year') result.eraYear = +value;
// TODO: remove this type annotation when `relatedYear` gets into TS lib types
if (type === ('relatedYear' as Intl.DateTimeFormatPartTypes)) result.eraYear = +value;
if (type === 'month') {
const matches = /^([0-9]*)(.*?)$/.exec(value);
if (!matches || matches.length != 3 || (!matches[1] && !matches[2])) {
throw new RangeError(`Unexpected month: ${value}`);
}
// If the month has no numeric part (should only see this for the Hebrew
// calendar with newer FF / Chromium versions; see
// https://bugzilla.mozilla.org/show_bug.cgi?id=1751833) then set a
// placeholder month index of `1` and rely on the derived class to
// calculate the correct month index from the month name stored in
// `monthExtra`.
result.month = matches[1] ? +matches[1] : 1;
if (result.month < 1) {
throw new RangeError(
`Invalid month ${value} from ${isoString}[u-ca-${this.id}]` +
' (probably due to https://bugs.chromium.org/p/v8/issues/detail?id=10527)'
);
}
if (result.month > 13) {
throw new RangeError(
`Invalid month ${value} from ${isoString}[u-ca-${this.id}]` +
' (probably due to https://bugs.chromium.org/p/v8/issues/detail?id=10529)'
);
}
// The ICU formats for the Hebrew calendar no longer support a numeric
// month format. So we'll rely on the derived class to interpret it.
// `monthExtra` is also used on the Chinese calendar to handle a suffix
// "bis" indicating a leap month.
if (matches[2]) result.monthExtra = matches[2];
}
if (type === 'day') result.day = +value;
if (this.hasEra && type === 'era' && value != null && value !== '') {
// The convention for Temporal era values is lowercase, so following
// that convention in this prototype. Punctuation is removed, accented
// letters are normalized, and spaces are replaced with dashes.
// E.g.: "ERA0" => "era0", "Before R.O.C." => "before-roc", "En’ō" => "eno"
// The call to normalize() and the replacement regex deals with era
// names that contain non-ASCII characters like Japanese eras. Also
// ignore extra content in parentheses like JPN era date ranges.
value = value.split(' (')[0];
result.era = value
.normalize('NFD')
.replace(/[^-0-9 \p{L}]/gu, '')
.replace(' ', '-')
.toLowerCase();
}
}
if (result.eraYear === undefined) {
// Node 12 has outdated ICU data that lacks the `relatedYear` field in the
// output of Intl.DateTimeFormat.formatToParts.
throw new RangeError(
`Intl.DateTimeFormat.formatToParts lacks relatedYear in ${this.id} calendar. Try Node 14+ or modern browsers.`
);
}
// Translate eras that may be handled differently by Temporal vs. by Intl
// (e.g. Japanese pre-Meiji eras). See https://github.com/tc39/proposal-temporal/issues/526.
if (this.reviseIntlEra) {
const { era, eraYear } = this.reviseIntlEra(result, isoDate);
result.era = era;
result.eraYear = eraYear;
}
if (this.checkIcuBugs) this.checkIcuBugs(isoDate);
const calendarDate = this.adjustCalendarDate(result, cache, 'constrain', true);
if (calendarDate.year === undefined) throw new RangeError(`Missing year converting ${JSON.stringify(isoDate)}`);
if (calendarDate.month === undefined) throw new RangeError(`Missing month converting ${JSON.stringify(isoDate)}`);
if (calendarDate.day === undefined) throw new RangeError(`Missing day converting ${JSON.stringify(isoDate)}`);
cache.set(key, calendarDate);
// Also cache the reverse mapping
['constrain', 'reject'].forEach((overflow) => {
const keyReverse = JSON.stringify({
func: 'calendarToIsoDate',
year: calendarDate.year,
month: calendarDate.month,
day: calendarDate.day,
overflow,
id: this.id
});
cache.set(keyReverse, isoDate);
});
return calendarDate;
}
validateCalendarDate(calendarDate: Partial<FullCalendarDate>): asserts calendarDate is FullCalendarDate {
const { era, month, year, day, eraYear, monthCode, monthExtra } = calendarDate;
// When there's a suffix (e.g. "5bis" for a leap month in Chinese calendar)
// the derived class must deal with it.
if (monthExtra !== undefined) throw new RangeError('Unexpected `monthExtra` value');
if (year === undefined && eraYear === undefined) throw new TypeError('year or eraYear is required');
if (month === undefined && monthCode === undefined) throw new TypeError('month or monthCode is required');
if (day === undefined) throw new RangeError('Missing day');
if (monthCode !== undefined) {
if (typeof monthCode !== 'string') {
throw new RangeError(`monthCode must be a string, not ${typeof monthCode}`);
}
if (!/^M([01]?\d)(L?)$/.test(monthCode)) throw new RangeError(`Invalid monthCode: ${monthCode}`);
}
if (this.constantEra) {
if (era !== undefined && era !== this.constantEra) {
throw new RangeError(`era must be ${this.constantEra}, not ${era}`);
}
if (eraYear !== undefined && year !== undefined && eraYear !== year) {
throw new RangeError(`eraYear ${eraYear} does not match year ${year}`);
}
}
if (this.hasEra) {
if ((calendarDate['era'] === undefined) !== (calendarDate['eraYear'] === undefined)) {
throw new RangeError("properties 'era' and 'eraYear' must be provided together");
}
}
}
/**
* Allows derived calendars to add additional fields and/or to make
* adjustments e.g. to set the era based on the date or to revise the month
* number in lunisolar calendars per
* https://github.com/tc39/proposal-temporal/issues/1203.
*
* The base implementation fills in missing values by assuming the simplest
* possible calendar:
* - no eras or a constant era defined in `.constantEra`
* - non-lunisolar calendar (no leap months)
* */
adjustCalendarDate(
calendarDateParam: Partial<FullCalendarDate>,
cache: OneObjectCache | undefined = undefined,
overflow: Overflow = 'constrain',
// This param is only used by derived classes
// eslint-disable-next-line @typescript-eslint/no-unused-vars
fromLegacyDate = false
): FullCalendarDate {
if (this.calendarType === 'lunisolar') throw new RangeError('Override required for lunisolar calendars');
let calendarDate = calendarDateParam;
this.validateCalendarDate(calendarDate);
// For calendars that always use the same era, set it here so that derived
// calendars won't need to implement this method simply to set the era.
if (this.constantEra) {
// year and eraYear always match when there's only one possible era
const { year, eraYear } = calendarDate;
calendarDate = {
...calendarDate,
era: this.constantEra,
year: year !== undefined ? year : eraYear,
eraYear: eraYear !== undefined ? eraYear : year
};
}
const largestMonth = this.monthsInYear(calendarDate as CalendarYearOnly, cache);
let { month, monthCode } = calendarDate;
({ month, monthCode } = resolveNonLunisolarMonth(calendarDate, overflow, largestMonth));
return { ...(calendarDate as typeof calendarDate & CalendarYMD), month, monthCode };
}
regulateMonthDayNaive(calendarDate: FullCalendarDate, overflow: Overflow, cache: OneObjectCache): FullCalendarDate {
const largestMonth = this.monthsInYear(calendarDate, cache);
let { month, day } = calendarDate;
if (overflow === 'reject') {
ES.RejectToRange(month, 1, largestMonth);
ES.RejectToRange(day, 1, this.maximumMonthLength(calendarDate));
} else {
month = ES.ConstrainToRange(month, 1, largestMonth);
day = ES.ConstrainToRange(day, 1, this.maximumMonthLength({ ...calendarDate, month }));
}
return { ...calendarDate, month, day };
}
calendarToIsoDate(dateParam: CalendarDateFields, overflow: Overflow = 'constrain', cache: OneObjectCache): IsoYMD {
const originalDate = dateParam as Partial<FullCalendarDate>;
// First, normalize the calendar date to ensure that (year, month, day)
// are all present, converting monthCode and eraYear if needed.
let date = this.adjustCalendarDate(dateParam, cache, overflow, false);
// Fix obviously out-of-bounds values. Values that are valid generally, but
// not in this particular year, may not be caught here for some calendars.
// If so, these will be handled lower below.
date = this.regulateMonthDayNaive(date, overflow, cache);
const { year, month, day } = date;
const key = JSON.stringify({ func: 'calendarToIsoDate', year, month, day, overflow, id: this.id });
let cached = cache.get(key);
if (cached) return cached;
// If YMD are present in the input but the input has been constrained
// already, then cache both the original value and the constrained value.
let keyOriginal;
if (
originalDate.year !== undefined &&
originalDate.month !== undefined &&
originalDate.day !== undefined &&
(originalDate.year !== date.year || originalDate.month !== date.month || originalDate.day !== date.day)
) {
keyOriginal = JSON.stringify({
func: 'calendarToIsoDate',
year: originalDate.year,
month: originalDate.month,
day: originalDate.day,
overflow,
id: this.id
});
cached = cache.get(keyOriginal);
if (cached) return cached;
}
// First, try to roughly guess the result
let isoEstimate = this.estimateIsoDate({ year, month, day });
const calculateSameMonthResult = (diffDays: number) => {
// If the estimate is in the same year & month as the target, then we can
// calculate the result exactly and short-circuit any additional logic.
// This optimization assumes that months are continuous. It would break if
// a calendar skipped days, like the Julian->Gregorian switchover. But
// current ICU calendars only skip days (japanese/roc/buddhist) because of
// a bug (https://bugs.chromium.org/p/chromium/issues/detail?id=1173158)
// that's currently worked around by a custom calendarToIsoDate
// implementation in those calendars. So this optimization should be safe
// for all ICU calendars.
let testIsoEstimate = this.addDaysIso(isoEstimate, diffDays);
if (date.day > this.minimumMonthLength(date)) {
// There's a chance that the calendar date is out of range. Throw or
// constrain if so.
let testCalendarDate = this.isoToCalendarDate(testIsoEstimate, cache);
while (testCalendarDate.month !== month || testCalendarDate.year !== year) {
if (overflow === 'reject') {
throw new RangeError(`day ${day} does not exist in month ${month} of year ${year}`);
}
// Back up a day at a time until we're not hanging over the month end
testIsoEstimate = this.addDaysIso(testIsoEstimate, -1);
testCalendarDate = this.isoToCalendarDate(testIsoEstimate, cache);
}
}
return testIsoEstimate;
};
let sign = 0;
let roundtripEstimate = this.isoToCalendarDate(isoEstimate, cache);
let diff = simpleDateDiff(date, roundtripEstimate);
if (diff.years !== 0 || diff.months !== 0 || diff.days !== 0) {
const diffTotalDaysEstimate = diff.years * 365 + diff.months * 30 + diff.days;
isoEstimate = this.addDaysIso(isoEstimate, diffTotalDaysEstimate);
roundtripEstimate = this.isoToCalendarDate(isoEstimate, cache);
diff = simpleDateDiff(date, roundtripEstimate);
if (diff.years === 0 && diff.months === 0) {
isoEstimate = calculateSameMonthResult(diff.days);
} else {
sign = this.compareCalendarDates(date, roundtripEstimate);
}
}
// If the initial guess is not in the same month, then then bisect the
// distance to the target, starting with 8 days per step.
let increment = 8;
while (sign) {
isoEstimate = this.addDaysIso(isoEstimate, sign * increment);