-
Notifications
You must be signed in to change notification settings - Fork 472
/
temporalHelpers.js
1246 lines (1152 loc) · 46.1 KB
/
temporalHelpers.js
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
// Copyright (C) 2021 Igalia, S.L. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
description: |
This defines helper objects and functions for testing Temporal.
defines: [TemporalHelpers]
features: [Symbol.species, Symbol.iterator, Temporal]
---*/
const ASCII_IDENTIFIER = /^[$_a-zA-Z][$_a-zA-Z0-9]*$/u;
function formatPropertyName(propertyKey, objectName = "") {
switch (typeof propertyKey) {
case "symbol":
if (Symbol.keyFor(propertyKey) !== undefined) {
return `${objectName}[Symbol.for('${Symbol.keyFor(propertyKey)}')]`;
} else if (propertyKey.description.startsWith('Symbol.')) {
return `${objectName}[${propertyKey.description}]`;
} else {
return `${objectName}[Symbol('${propertyKey.description}')]`
}
case "string":
if (propertyKey !== String(Number(propertyKey))) {
if (ASCII_IDENTIFIER.test(propertyKey)) {
return objectName ? `${objectName}.${propertyKey}` : propertyKey;
}
return `${objectName}['${propertyKey.replace(/'/g, "\\'")}']`
}
// fall through
default:
// integer or string integer-index
return `${objectName}[${propertyKey}]`;
}
}
const SKIP_SYMBOL = Symbol("Skip");
var TemporalHelpers = {
/*
* Codes and maximum lengths of months in the ISO 8601 calendar.
*/
ISOMonths: [
{ month: 1, monthCode: "M01", daysInMonth: 31 },
{ month: 2, monthCode: "M02", daysInMonth: 29 },
{ month: 3, monthCode: "M03", daysInMonth: 31 },
{ month: 4, monthCode: "M04", daysInMonth: 30 },
{ month: 5, monthCode: "M05", daysInMonth: 31 },
{ month: 6, monthCode: "M06", daysInMonth: 30 },
{ month: 7, monthCode: "M07", daysInMonth: 31 },
{ month: 8, monthCode: "M08", daysInMonth: 31 },
{ month: 9, monthCode: "M09", daysInMonth: 30 },
{ month: 10, monthCode: "M10", daysInMonth: 31 },
{ month: 11, monthCode: "M11", daysInMonth: 30 },
{ month: 12, monthCode: "M12", daysInMonth: 31 }
],
/*
* List of known calendar eras and their possible aliases.
*
* https://tc39.es/proposal-intl-era-monthcode/#table-eras
*/
CalendarEras: {
buddhist: [
{ era: "buddhist", aliases: ["be"] },
],
chinese: [
{ era: "chinese" },
],
coptic: [
{ era: "coptic" },
{ era: "coptic-inverse" },
],
dangi: [
{ era: "dangi" },
],
ethiopic: [
{ era: "ethiopic", aliases: ["incar"] },
{ era: "ethioaa", aliases: ["ethiopic-amete-alem", "mundi"] },
],
ethioaa: [
{ era: "ethioaa", aliases: ["ethiopic-amete-alem", "mundi"] },
],
gregory: [
{ era: "gregory", aliases: ["ce", "ad"] },
{ era: "gregory-inverse", aliases: ["bc", "bce"] },
],
hebrew: [
{ era: "hebrew", aliases: ["am"] },
],
indian: [
{ era: "indian", aliases: ["saka"] },
],
islamic: [
{ era: "islamic", aliases: ["ah"] },
],
"islamic-civil": [
{ era: "islamic-civil", aliases: ["islamicc", "ah"] },
],
"islamic-rgsa": [
{ era: "islamic-rgsa", aliases: ["ah"] },
],
"islamic-tbla": [
{ era: "islamic-tbla", aliases: ["ah"] },
],
"islamic-umalqura": [
{ era: "islamic-umalqura", aliases: ["ah"] },
],
japanese: [
{ era: "heisei" },
{ era: "japanese", aliases: ["gregory", "ad", "ce"] },
{ era: "japanese-inverse", aliases: ["gregory-inverse", "bc", "bce"] },
{ era: "meiji" },
{ era: "reiwa" },
{ era: "showa" },
{ era: "taisho" },
],
persian: [
{ era: "persian", aliases: ["ap"] },
],
roc: [
{ era: "roc", aliases: ["minguo"] },
{ era: "roc-inverse", aliases: ["before-roc"] },
],
},
/*
* Return the canonical era code.
*/
canonicalizeCalendarEra(calendarId, eraName) {
assert.sameValue(typeof calendarId, "string", "calendar must be string in canonicalizeCalendarEra");
if (calendarId === "iso8601") {
assert.sameValue(eraName, undefined);
return undefined;
}
assert(Object.hasOwn(TemporalHelpers.CalendarEras, calendarId));
if (eraName === undefined) {
return undefined;
}
assert.sameValue(typeof eraName, "string", "eraName must be string or undefined in canonicalizeCalendarEra");
for (let {era, aliases = []} of TemporalHelpers.CalendarEras[calendarId]) {
if (era === eraName || aliases.includes(eraName)) {
return era;
}
}
throw new Test262Error(`Unsupported era name: ${eraName}`);
},
/*
* assertDuration(duration, years, ..., nanoseconds[, description]):
*
* Shorthand for asserting that each field of a Temporal.Duration is equal to
* an expected value.
*/
assertDuration(duration, years, months, weeks, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds, description = "") {
const prefix = description ? `${description}: ` : "";
assert(duration instanceof Temporal.Duration, `${prefix}instanceof`);
assert.sameValue(duration.years, years, `${prefix}years result:`);
assert.sameValue(duration.months, months, `${prefix}months result:`);
assert.sameValue(duration.weeks, weeks, `${prefix}weeks result:`);
assert.sameValue(duration.days, days, `${prefix}days result:`);
assert.sameValue(duration.hours, hours, `${prefix}hours result:`);
assert.sameValue(duration.minutes, minutes, `${prefix}minutes result:`);
assert.sameValue(duration.seconds, seconds, `${prefix}seconds result:`);
assert.sameValue(duration.milliseconds, milliseconds, `${prefix}milliseconds result:`);
assert.sameValue(duration.microseconds, microseconds, `${prefix}microseconds result:`);
assert.sameValue(duration.nanoseconds, nanoseconds, `${prefix}nanoseconds result`);
},
/*
* assertDateDuration(duration, years, months, weeks, days, [, description]):
*
* Shorthand for asserting that each date field of a Temporal.Duration is
* equal to an expected value.
*/
assertDateDuration(duration, years, months, weeks, days, description = "") {
const prefix = description ? `${description}: ` : "";
assert(duration instanceof Temporal.Duration, `${prefix}instanceof`);
assert.sameValue(duration.years, years, `${prefix}years result:`);
assert.sameValue(duration.months, months, `${prefix}months result:`);
assert.sameValue(duration.weeks, weeks, `${prefix}weeks result:`);
assert.sameValue(duration.days, days, `${prefix}days result:`);
assert.sameValue(duration.hours, 0, `${prefix}hours result should be zero:`);
assert.sameValue(duration.minutes, 0, `${prefix}minutes result should be zero:`);
assert.sameValue(duration.seconds, 0, `${prefix}seconds result should be zero:`);
assert.sameValue(duration.milliseconds, 0, `${prefix}milliseconds result should be zero:`);
assert.sameValue(duration.microseconds, 0, `${prefix}microseconds result should be zero:`);
assert.sameValue(duration.nanoseconds, 0, `${prefix}nanoseconds result should be zero:`);
},
/*
* assertDurationsEqual(actual, expected[, description]):
*
* Shorthand for asserting that each field of a Temporal.Duration is equal to
* the corresponding field in another Temporal.Duration.
*/
assertDurationsEqual(actual, expected, description = "") {
const prefix = description ? `${description}: ` : "";
assert(expected instanceof Temporal.Duration, `${prefix}expected value should be a Temporal.Duration`);
TemporalHelpers.assertDuration(actual, expected.years, expected.months, expected.weeks, expected.days, expected.hours, expected.minutes, expected.seconds, expected.milliseconds, expected.microseconds, expected.nanoseconds, description);
},
/*
* assertInstantsEqual(actual, expected[, description]):
*
* Shorthand for asserting that two Temporal.Instants are of the correct type
* and equal according to their equals() methods.
*/
assertInstantsEqual(actual, expected, description = "") {
const prefix = description ? `${description}: ` : "";
assert(expected instanceof Temporal.Instant, `${prefix}expected value should be a Temporal.Instant`);
assert(actual instanceof Temporal.Instant, `${prefix}instanceof`);
assert(actual.equals(expected), `${prefix}equals method`);
},
/*
* assertPlainDate(date, year, ..., nanosecond[, description[, era, eraYear]]):
*
* Shorthand for asserting that each field of a Temporal.PlainDate is equal to
* an expected value. (Except the `calendar` property, since callers may want
* to assert either object equality with an object they put in there, or the
* value of date.calendarId.)
*/
assertPlainDate(date, year, month, monthCode, day, description = "", era = undefined, eraYear = undefined) {
const prefix = description ? `${description}: ` : "";
assert(date instanceof Temporal.PlainDate, `${prefix}instanceof`);
assert.sameValue(
TemporalHelpers.canonicalizeCalendarEra(date.calendarId, date.era),
TemporalHelpers.canonicalizeCalendarEra(date.calendarId, era),
`${prefix}era result:`
);
assert.sameValue(date.eraYear, eraYear, `${prefix}eraYear result:`);
assert.sameValue(date.year, year, `${prefix}year result:`);
assert.sameValue(date.month, month, `${prefix}month result:`);
assert.sameValue(date.monthCode, monthCode, `${prefix}monthCode result:`);
assert.sameValue(date.day, day, `${prefix}day result:`);
},
/*
* assertPlainDateTime(datetime, year, ..., nanosecond[, description[, era, eraYear]]):
*
* Shorthand for asserting that each field of a Temporal.PlainDateTime is
* equal to an expected value. (Except the `calendar` property, since callers
* may want to assert either object equality with an object they put in there,
* or the value of datetime.calendarId.)
*/
assertPlainDateTime(datetime, year, month, monthCode, day, hour, minute, second, millisecond, microsecond, nanosecond, description = "", era = undefined, eraYear = undefined) {
const prefix = description ? `${description}: ` : "";
assert(datetime instanceof Temporal.PlainDateTime, `${prefix}instanceof`);
assert.sameValue(
TemporalHelpers.canonicalizeCalendarEra(datetime.calendarId, datetime.era),
TemporalHelpers.canonicalizeCalendarEra(datetime.calendarId, era),
`${prefix}era result:`
);
assert.sameValue(datetime.eraYear, eraYear, `${prefix}eraYear result:`);
assert.sameValue(datetime.year, year, `${prefix}year result:`);
assert.sameValue(datetime.month, month, `${prefix}month result:`);
assert.sameValue(datetime.monthCode, monthCode, `${prefix}monthCode result:`);
assert.sameValue(datetime.day, day, `${prefix}day result:`);
assert.sameValue(datetime.hour, hour, `${prefix}hour result:`);
assert.sameValue(datetime.minute, minute, `${prefix}minute result:`);
assert.sameValue(datetime.second, second, `${prefix}second result:`);
assert.sameValue(datetime.millisecond, millisecond, `${prefix}millisecond result:`);
assert.sameValue(datetime.microsecond, microsecond, `${prefix}microsecond result:`);
assert.sameValue(datetime.nanosecond, nanosecond, `${prefix}nanosecond result:`);
},
/*
* assertPlainDateTimesEqual(actual, expected[, description]):
*
* Shorthand for asserting that two Temporal.PlainDateTimes are of the correct
* type, equal according to their equals() methods, and additionally that
* their calendar internal slots are the same value.
*/
assertPlainDateTimesEqual(actual, expected, description = "") {
const prefix = description ? `${description}: ` : "";
assert(expected instanceof Temporal.PlainDateTime, `${prefix}expected value should be a Temporal.PlainDateTime`);
assert(actual instanceof Temporal.PlainDateTime, `${prefix}instanceof`);
assert(actual.equals(expected), `${prefix}equals method`);
assert.sameValue(
actual.calendarId,
expected.calendarId,
`${prefix}calendar same value:`
);
},
/*
* assertPlainMonthDay(monthDay, monthCode, day[, description [, referenceISOYear]]):
*
* Shorthand for asserting that each field of a Temporal.PlainMonthDay is
* equal to an expected value. (Except the `calendar` property, since callers
* may want to assert either object equality with an object they put in there,
* or the value of monthDay.calendarId().)
*/
assertPlainMonthDay(monthDay, monthCode, day, description = "", referenceISOYear = 1972) {
const prefix = description ? `${description}: ` : "";
assert(monthDay instanceof Temporal.PlainMonthDay, `${prefix}instanceof`);
assert.sameValue(monthDay.monthCode, monthCode, `${prefix}monthCode result:`);
assert.sameValue(monthDay.day, day, `${prefix}day result:`);
const isoYear = Number(monthDay.toString({ calendarName: "always" }).split("-")[0]);
assert.sameValue(isoYear, referenceISOYear, `${prefix}referenceISOYear result:`);
},
/*
* assertPlainTime(time, hour, ..., nanosecond[, description]):
*
* Shorthand for asserting that each field of a Temporal.PlainTime is equal to
* an expected value.
*/
assertPlainTime(time, hour, minute, second, millisecond, microsecond, nanosecond, description = "") {
const prefix = description ? `${description}: ` : "";
assert(time instanceof Temporal.PlainTime, `${prefix}instanceof`);
assert.sameValue(time.hour, hour, `${prefix}hour result:`);
assert.sameValue(time.minute, minute, `${prefix}minute result:`);
assert.sameValue(time.second, second, `${prefix}second result:`);
assert.sameValue(time.millisecond, millisecond, `${prefix}millisecond result:`);
assert.sameValue(time.microsecond, microsecond, `${prefix}microsecond result:`);
assert.sameValue(time.nanosecond, nanosecond, `${prefix}nanosecond result:`);
},
/*
* assertPlainTimesEqual(actual, expected[, description]):
*
* Shorthand for asserting that two Temporal.PlainTimes are of the correct
* type and equal according to their equals() methods.
*/
assertPlainTimesEqual(actual, expected, description = "") {
const prefix = description ? `${description}: ` : "";
assert(expected instanceof Temporal.PlainTime, `${prefix}expected value should be a Temporal.PlainTime`);
assert(actual instanceof Temporal.PlainTime, `${prefix}instanceof`);
assert(actual.equals(expected), `${prefix}equals method`);
},
/*
* assertPlainYearMonth(yearMonth, year, month, monthCode[, description[, era, eraYear, referenceISODay]]):
*
* Shorthand for asserting that each field of a Temporal.PlainYearMonth is
* equal to an expected value. (Except the `calendar` property, since callers
* may want to assert either object equality with an object they put in there,
* or the value of yearMonth.calendarId.)
*/
assertPlainYearMonth(yearMonth, year, month, monthCode, description = "", era = undefined, eraYear = undefined, referenceISODay = 1) {
const prefix = description ? `${description}: ` : "";
assert(yearMonth instanceof Temporal.PlainYearMonth, `${prefix}instanceof`);
assert.sameValue(
TemporalHelpers.canonicalizeCalendarEra(yearMonth.calendarId, yearMonth.era),
TemporalHelpers.canonicalizeCalendarEra(yearMonth.calendarId, era),
`${prefix}era result:`
);
assert.sameValue(yearMonth.eraYear, eraYear, `${prefix}eraYear result:`);
assert.sameValue(yearMonth.year, year, `${prefix}year result:`);
assert.sameValue(yearMonth.month, month, `${prefix}month result:`);
assert.sameValue(yearMonth.monthCode, monthCode, `${prefix}monthCode result:`);
const isoDay = Number(yearMonth.toString({ calendarName: "always" }).slice(1).split('-')[2].slice(0, 2));
assert.sameValue(isoDay, referenceISODay, `${prefix}referenceISODay result:`);
},
/*
* assertZonedDateTimesEqual(actual, expected[, description]):
*
* Shorthand for asserting that two Temporal.ZonedDateTimes are of the correct
* type, equal according to their equals() methods, and additionally that
* their time zones and calendar internal slots are the same value.
*/
assertZonedDateTimesEqual(actual, expected, description = "") {
const prefix = description ? `${description}: ` : "";
assert(expected instanceof Temporal.ZonedDateTime, `${prefix}expected value should be a Temporal.ZonedDateTime`);
assert(actual instanceof Temporal.ZonedDateTime, `${prefix}instanceof`);
assert(actual.equals(expected), `${prefix}equals method`);
assert.sameValue(actual.timeZone, expected.timeZone, `${prefix}time zone same value:`);
assert.sameValue(
actual.calendarId,
expected.calendarId,
`${prefix}calendar same value:`
);
},
/*
* assertUnreachable(description):
*
* Helper for asserting that code is not executed.
*/
assertUnreachable(description) {
let message = "This code should not be executed";
if (description) {
message = `${message}: ${description}`;
}
throw new Test262Error(message);
},
/*
* checkPlainDateTimeConversionFastPath(func):
*
* ToTemporalDate and ToTemporalTime should both, if given a
* Temporal.PlainDateTime instance, convert to the desired type by reading the
* PlainDateTime's internal slots, rather than calling any getters.
*
* func(datetime) is the actual operation to test, that must
* internally call the abstract operation ToTemporalDate or ToTemporalTime.
* It is passed a Temporal.PlainDateTime instance.
*/
checkPlainDateTimeConversionFastPath(func, message = "checkPlainDateTimeConversionFastPath") {
const actual = [];
const expected = [];
const calendar = "iso8601";
const datetime = new Temporal.PlainDateTime(2000, 5, 2, 12, 34, 56, 987, 654, 321, calendar);
const prototypeDescrs = Object.getOwnPropertyDescriptors(Temporal.PlainDateTime.prototype);
["year", "month", "monthCode", "day", "hour", "minute", "second", "millisecond", "microsecond", "nanosecond"].forEach((property) => {
Object.defineProperty(datetime, property, {
get() {
actual.push(`get ${formatPropertyName(property)}`);
const value = prototypeDescrs[property].get.call(this);
return {
toString() {
actual.push(`toString ${formatPropertyName(property)}`);
return value.toString();
},
valueOf() {
actual.push(`valueOf ${formatPropertyName(property)}`);
return value;
},
};
},
});
});
Object.defineProperty(datetime, "calendar", {
get() {
actual.push("get calendar");
return calendar;
},
});
func(datetime);
assert.compareArray(actual, expected, `${message}: property getters not called`);
},
/*
* Check that an options bag that accepts units written in the singular form,
* also accepts the same units written in the plural form.
* func(unit) should call the method with the appropriate options bag
* containing unit as a value. This will be called twice for each element of
* validSingularUnits, once with singular and once with plural, and the
* results of each pair should be the same (whether a Temporal object or a
* primitive value.)
*/
checkPluralUnitsAccepted(func, validSingularUnits) {
const plurals = {
year: 'years',
month: 'months',
week: 'weeks',
day: 'days',
hour: 'hours',
minute: 'minutes',
second: 'seconds',
millisecond: 'milliseconds',
microsecond: 'microseconds',
nanosecond: 'nanoseconds',
};
validSingularUnits.forEach((unit) => {
const singularValue = func(unit);
const pluralValue = func(plurals[unit]);
const desc = `Plural ${plurals[unit]} produces the same result as singular ${unit}`;
if (singularValue instanceof Temporal.Duration) {
TemporalHelpers.assertDurationsEqual(pluralValue, singularValue, desc);
} else if (singularValue instanceof Temporal.Instant) {
TemporalHelpers.assertInstantsEqual(pluralValue, singularValue, desc);
} else if (singularValue instanceof Temporal.PlainDateTime) {
TemporalHelpers.assertPlainDateTimesEqual(pluralValue, singularValue, desc);
} else if (singularValue instanceof Temporal.PlainTime) {
TemporalHelpers.assertPlainTimesEqual(pluralValue, singularValue, desc);
} else if (singularValue instanceof Temporal.ZonedDateTime) {
TemporalHelpers.assertZonedDateTimesEqual(pluralValue, singularValue, desc);
} else {
assert.sameValue(pluralValue, singularValue);
}
});
},
/*
* checkRoundingIncrementOptionWrongType(checkFunc, assertTrueResultFunc, assertObjectResultFunc):
*
* Checks the type handling of the roundingIncrement option.
* checkFunc(roundingIncrement) is a function which takes the value of
* roundingIncrement to test, and calls the method under test with it,
* returning the result. assertTrueResultFunc(result, description) should
* assert that result is the expected result with roundingIncrement: true, and
* assertObjectResultFunc(result, description) should assert that result is
* the expected result with roundingIncrement being an object with a valueOf()
* method.
*/
checkRoundingIncrementOptionWrongType(checkFunc, assertTrueResultFunc, assertObjectResultFunc) {
// null converts to 0, which is out of range
assert.throws(RangeError, () => checkFunc(null), "null");
// Booleans convert to either 0 or 1, and 1 is allowed
const trueResult = checkFunc(true);
assertTrueResultFunc(trueResult, "true");
assert.throws(RangeError, () => checkFunc(false), "false");
// Symbols and BigInts cannot convert to numbers
assert.throws(TypeError, () => checkFunc(Symbol()), "symbol");
assert.throws(TypeError, () => checkFunc(2n), "bigint");
// Objects prefer their valueOf() methods when converting to a number
assert.throws(RangeError, () => checkFunc({}), "plain object");
const expected = [
"get roundingIncrement.valueOf",
"call roundingIncrement.valueOf",
];
const actual = [];
const observer = TemporalHelpers.toPrimitiveObserver(actual, 2, "roundingIncrement");
const objectResult = checkFunc(observer);
assertObjectResultFunc(objectResult, "object with valueOf");
assert.compareArray(actual, expected, "order of operations");
},
/*
* checkStringOptionWrongType(propertyName, value, checkFunc, assertFunc):
*
* Checks the type handling of a string option, of which there are several in
* Temporal.
* propertyName is the name of the option, and value is the value that
* assertFunc should expect it to have.
* checkFunc(value) is a function which takes the value of the option to test,
* and calls the method under test with it, returning the result.
* assertFunc(result, description) should assert that result is the expected
* result with the option value being an object with a toString() method
* which returns the given value.
*/
checkStringOptionWrongType(propertyName, value, checkFunc, assertFunc) {
// null converts to the string "null", which is an invalid string value
assert.throws(RangeError, () => checkFunc(null), "null");
// Booleans convert to the strings "true" or "false", which are invalid
assert.throws(RangeError, () => checkFunc(true), "true");
assert.throws(RangeError, () => checkFunc(false), "false");
// Symbols cannot convert to strings
assert.throws(TypeError, () => checkFunc(Symbol()), "symbol");
// Numbers convert to strings which are invalid
assert.throws(RangeError, () => checkFunc(2), "number");
// BigInts convert to strings which are invalid
assert.throws(RangeError, () => checkFunc(2n), "bigint");
// Objects prefer their toString() methods when converting to a string
assert.throws(RangeError, () => checkFunc({}), "plain object");
const expected = [
`get ${propertyName}.toString`,
`call ${propertyName}.toString`,
];
const actual = [];
const observer = TemporalHelpers.toPrimitiveObserver(actual, value, propertyName);
const result = checkFunc(observer);
assertFunc(result, "object with toString");
assert.compareArray(actual, expected, "order of operations");
},
/*
* checkSubclassingIgnored(construct, constructArgs, method, methodArgs,
* resultAssertions):
*
* Methods of Temporal classes that return a new instance of the same class,
* must not take the constructor of a subclass into account, nor the @@species
* property. This helper runs tests to ensure this.
*
* construct(...constructArgs) must yield a valid instance of the Temporal
* class. instance[method](...methodArgs) is the method call under test, which
* must also yield a valid instance of the same Temporal class, not a
* subclass. See below for the individual tests that this runs.
* resultAssertions() is a function that performs additional assertions on the
* instance returned by the method under test.
*/
checkSubclassingIgnored(...args) {
this.checkSubclassConstructorNotObject(...args);
this.checkSubclassConstructorUndefined(...args);
this.checkSubclassConstructorThrows(...args);
this.checkSubclassConstructorNotCalled(...args);
this.checkSubclassSpeciesInvalidResult(...args);
this.checkSubclassSpeciesNotAConstructor(...args);
this.checkSubclassSpeciesNull(...args);
this.checkSubclassSpeciesUndefined(...args);
this.checkSubclassSpeciesThrows(...args);
},
/*
* Checks that replacing the 'constructor' property of the instance with
* various primitive values does not affect the returned new instance.
*/
checkSubclassConstructorNotObject(construct, constructArgs, method, methodArgs, resultAssertions) {
function check(value, description) {
const instance = new construct(...constructArgs);
instance.constructor = value;
const result = instance[method](...methodArgs);
assert.sameValue(Object.getPrototypeOf(result), construct.prototype, description);
resultAssertions(result);
}
check(null, "null");
check(true, "true");
check("test", "string");
check(Symbol(), "Symbol");
check(7, "number");
check(7n, "bigint");
},
/*
* Checks that replacing the 'constructor' property of the subclass with
* undefined does not affect the returned new instance.
*/
checkSubclassConstructorUndefined(construct, constructArgs, method, methodArgs, resultAssertions) {
let called = 0;
class MySubclass extends construct {
constructor() {
++called;
super(...constructArgs);
}
}
const instance = new MySubclass();
assert.sameValue(called, 1);
MySubclass.prototype.constructor = undefined;
const result = instance[method](...methodArgs);
assert.sameValue(called, 1);
assert.sameValue(Object.getPrototypeOf(result), construct.prototype);
resultAssertions(result);
},
/*
* Checks that making the 'constructor' property of the instance throw when
* called does not affect the returned new instance.
*/
checkSubclassConstructorThrows(construct, constructArgs, method, methodArgs, resultAssertions) {
function CustomError() {}
const instance = new construct(...constructArgs);
Object.defineProperty(instance, "constructor", {
get() {
throw new CustomError();
}
});
const result = instance[method](...methodArgs);
assert.sameValue(Object.getPrototypeOf(result), construct.prototype);
resultAssertions(result);
},
/*
* Checks that when subclassing, the subclass constructor is not called by
* the method under test.
*/
checkSubclassConstructorNotCalled(construct, constructArgs, method, methodArgs, resultAssertions) {
let called = 0;
class MySubclass extends construct {
constructor() {
++called;
super(...constructArgs);
}
}
const instance = new MySubclass();
assert.sameValue(called, 1);
const result = instance[method](...methodArgs);
assert.sameValue(called, 1);
assert.sameValue(Object.getPrototypeOf(result), construct.prototype);
resultAssertions(result);
},
/*
* Check that the constructor's @@species property is ignored when it's a
* constructor that returns a non-object value.
*/
checkSubclassSpeciesInvalidResult(construct, constructArgs, method, methodArgs, resultAssertions) {
function check(value, description) {
const instance = new construct(...constructArgs);
instance.constructor = {
[Symbol.species]: function() {
return value;
},
};
const result = instance[method](...methodArgs);
assert.sameValue(Object.getPrototypeOf(result), construct.prototype, description);
resultAssertions(result);
}
check(undefined, "undefined");
check(null, "null");
check(true, "true");
check("test", "string");
check(Symbol(), "Symbol");
check(7, "number");
check(7n, "bigint");
check({}, "plain object");
},
/*
* Check that the constructor's @@species property is ignored when it's not a
* constructor.
*/
checkSubclassSpeciesNotAConstructor(construct, constructArgs, method, methodArgs, resultAssertions) {
function check(value, description) {
const instance = new construct(...constructArgs);
instance.constructor = {
[Symbol.species]: value,
};
const result = instance[method](...methodArgs);
assert.sameValue(Object.getPrototypeOf(result), construct.prototype, description);
resultAssertions(result);
}
check(true, "true");
check("test", "string");
check(Symbol(), "Symbol");
check(7, "number");
check(7n, "bigint");
check({}, "plain object");
},
/*
* Check that the constructor's @@species property is ignored when it's null.
*/
checkSubclassSpeciesNull(construct, constructArgs, method, methodArgs, resultAssertions) {
let called = 0;
class MySubclass extends construct {
constructor() {
++called;
super(...constructArgs);
}
}
const instance = new MySubclass();
assert.sameValue(called, 1);
MySubclass.prototype.constructor = {
[Symbol.species]: null,
};
const result = instance[method](...methodArgs);
assert.sameValue(called, 1);
assert.sameValue(Object.getPrototypeOf(result), construct.prototype);
resultAssertions(result);
},
/*
* Check that the constructor's @@species property is ignored when it's
* undefined.
*/
checkSubclassSpeciesUndefined(construct, constructArgs, method, methodArgs, resultAssertions) {
let called = 0;
class MySubclass extends construct {
constructor() {
++called;
super(...constructArgs);
}
}
const instance = new MySubclass();
assert.sameValue(called, 1);
MySubclass.prototype.constructor = {
[Symbol.species]: undefined,
};
const result = instance[method](...methodArgs);
assert.sameValue(called, 1);
assert.sameValue(Object.getPrototypeOf(result), construct.prototype);
resultAssertions(result);
},
/*
* Check that the constructor's @@species property is ignored when it throws,
* i.e. it is not called at all.
*/
checkSubclassSpeciesThrows(construct, constructArgs, method, methodArgs, resultAssertions) {
function CustomError() {}
const instance = new construct(...constructArgs);
instance.constructor = {
get [Symbol.species]() {
throw new CustomError();
},
};
const result = instance[method](...methodArgs);
assert.sameValue(Object.getPrototypeOf(result), construct.prototype);
},
/*
* checkSubclassingIgnoredStatic(construct, method, methodArgs, resultAssertions):
*
* Static methods of Temporal classes that return a new instance of the class,
* must not use the this-value as a constructor. This helper runs tests to
* ensure this.
*
* construct[method](...methodArgs) is the static method call under test, and
* must yield a valid instance of the Temporal class, not a subclass. See
* below for the individual tests that this runs.
* resultAssertions() is a function that performs additional assertions on the
* instance returned by the method under test.
*/
checkSubclassingIgnoredStatic(...args) {
this.checkStaticInvalidReceiver(...args);
this.checkStaticReceiverNotCalled(...args);
this.checkThisValueNotCalled(...args);
},
/*
* Check that calling the static method with a receiver that's not callable,
* still calls the intrinsic constructor.
*/
checkStaticInvalidReceiver(construct, method, methodArgs, resultAssertions) {
function check(value, description) {
const result = construct[method].apply(value, methodArgs);
assert.sameValue(Object.getPrototypeOf(result), construct.prototype);
resultAssertions(result);
}
check(undefined, "undefined");
check(null, "null");
check(true, "true");
check("test", "string");
check(Symbol(), "symbol");
check(7, "number");
check(7n, "bigint");
check({}, "Non-callable object");
},
/*
* Check that calling the static method with a receiver that returns a value
* that's not callable, still calls the intrinsic constructor.
*/
checkStaticReceiverNotCalled(construct, method, methodArgs, resultAssertions) {
function check(value, description) {
const receiver = function () {
return value;
};
const result = construct[method].apply(receiver, methodArgs);
assert.sameValue(Object.getPrototypeOf(result), construct.prototype);
resultAssertions(result);
}
check(undefined, "undefined");
check(null, "null");
check(true, "true");
check("test", "string");
check(Symbol(), "symbol");
check(7, "number");
check(7n, "bigint");
check({}, "Non-callable object");
},
/*
* Check that the receiver isn't called.
*/
checkThisValueNotCalled(construct, method, methodArgs, resultAssertions) {
let called = false;
class MySubclass extends construct {
constructor(...args) {
called = true;
super(...args);
}
}
const result = MySubclass[method](...methodArgs);
assert.sameValue(called, false);
assert.sameValue(Object.getPrototypeOf(result), construct.prototype);
resultAssertions(result);
},
/*
* Check that any calendar-carrying Temporal object has its [[Calendar]]
* internal slot read by ToTemporalCalendar, and does not fetch the calendar
* by calling getters.
*/
checkToTemporalCalendarFastPath(func) {
const plainDate = new Temporal.PlainDate(2000, 5, 2, "iso8601");
const plainDateTime = new Temporal.PlainDateTime(2000, 5, 2, 12, 34, 56, 987, 654, 321, "iso8601");
const plainMonthDay = new Temporal.PlainMonthDay(5, 2, "iso8601");
const plainYearMonth = new Temporal.PlainYearMonth(2000, 5, "iso8601");
const zonedDateTime = new Temporal.ZonedDateTime(1_000_000_000_000_000_000n, "UTC", "iso8601");
[plainDate, plainDateTime, plainMonthDay, plainYearMonth, zonedDateTime].forEach((temporalObject) => {
const actual = [];
const expected = [];
Object.defineProperty(temporalObject, "calendar", {
get() {
actual.push("get calendar");
return calendar;
},
});
func(temporalObject);
assert.compareArray(actual, expected, "calendar getter not called");
});
},
checkToTemporalInstantFastPath(func) {
const actual = [];
const expected = [];
const datetime = new Temporal.ZonedDateTime(1_000_000_000_987_654_321n, "UTC");
Object.defineProperty(datetime, 'toString', {
get() {
actual.push("get toString");
return function (options) {
actual.push("call toString");
return Temporal.ZonedDateTime.prototype.toString.call(this, options);
};
},
});
func(datetime);
assert.compareArray(actual, expected, "toString not called");
},
checkToTemporalPlainDateTimeFastPath(func) {
const actual = [];
const expected = [];
const date = new Temporal.PlainDate(2000, 5, 2, "iso8601");
const prototypeDescrs = Object.getOwnPropertyDescriptors(Temporal.PlainDate.prototype);
["year", "month", "monthCode", "day"].forEach((property) => {
Object.defineProperty(date, property, {
get() {
actual.push(`get ${formatPropertyName(property)}`);
const value = prototypeDescrs[property].get.call(this);
return TemporalHelpers.toPrimitiveObserver(actual, value, property);
},
});
});
["hour", "minute", "second", "millisecond", "microsecond", "nanosecond"].forEach((property) => {
Object.defineProperty(date, property, {
get() {
actual.push(`get ${formatPropertyName(property)}`);
return undefined;
},
});
});
Object.defineProperty(date, "calendar", {
get() {
actual.push("get calendar");
return "iso8601";
},
});
func(date);
assert.compareArray(actual, expected, "property getters not called");
},
/*
* observeProperty(calls, object, propertyName, value):
*
* Defines an own property @object.@propertyName with value @value, that
* will log any calls to its accessors to the array @calls.
*/
observeProperty(calls, object, propertyName, value, objectName = "") {
Object.defineProperty(object, propertyName, {
get() {
calls.push(`get ${formatPropertyName(propertyName, objectName)}`);
return value;
},
set(v) {
calls.push(`set ${formatPropertyName(propertyName, objectName)}`);
}
});
},
/*
* observeMethod(calls, object, propertyName, value):
*
* Defines an own property @object.@propertyName with value @value, that
* will log any calls of @value to the array @calls.
*/
observeMethod(calls, object, propertyName, objectName = "") {
const method = object[propertyName];
object[propertyName] = function () {
calls.push(`call ${formatPropertyName(propertyName, objectName)}`);
return method.apply(object, arguments);
};
},
/*
* Used for substituteMethod to indicate default behavior instead of a
* substituted value
*/
SUBSTITUTE_SKIP: SKIP_SYMBOL,
/*
* substituteMethod(object, propertyName, values):
*
* Defines an own property @object.@propertyName that will, for each
* subsequent call to the method previously defined as