Skip to content

Commit

Permalink
Bail out early in non-ISO Calendars when calculating the duration
Browse files Browse the repository at this point in the history
between two identical dates.
  • Loading branch information
12wrigja committed Sep 7, 2022
1 parent 02ae80d commit 6f3c42c
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 0 deletions.
3 changes: 3 additions & 0 deletions lib/calendar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1131,6 +1131,9 @@ abstract class HelperBase {
const diffMonths = calendarTwo.month - calendarOne.month;
const diffDays = calendarTwo.day - calendarOne.day;
const sign = this.compareCalendarDates(calendarTwo, calendarOne);
if (!sign) {
return { years: 0, months: 0, weeks: 0, days: 0 };
}
if (largestUnit === 'year' && diffYears) {
const isOneFurtherInYear = diffMonths * sign < 0 || (diffMonths === 0 && diffDays * sign < 0);
years = isOneFurtherInYear ? diffYears - sign : diffYears;
Expand Down
4 changes: 4 additions & 0 deletions test/calendar.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -404,6 +404,10 @@ describe('Built-in calendars (not standardized yet)', () => {
const date = Temporal.PlainDate.from({ era: 'bce', eraYear: 2, month: 12, day: 31, calendar: 'gregory' });
equal(`${date}`, '-000001-12-31[u-ca=gregory]');
});
it('does not infinite loop', () => {
const nowZoned = Temporal.Now.zonedDateTime('gregory');
equal(Temporal.Duration.from('PT0S').total({ unit: 'years', relativeTo: nowZoned }), 0);
});
});
});

Expand Down

0 comments on commit 6f3c42c

Please sign in to comment.