Skip to content

Commit

Permalink
Duration.toJSON() should not print unwanted zeroes
Browse files Browse the repository at this point in the history
Due to a missing argument, Temporal.Duration.from({ hours: 1 }).toJSON()
would return "PT1H0.0S" instead of "PT1H". The same goes for
toLocaleString() in the absence of Intl.DurationFormat.

No change needed to the spec text or documentation, which are already
correct.
  • Loading branch information
ptomato committed Feb 18, 2021
1 parent 5be251f commit 3b9e891
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 2 deletions.
4 changes: 2 additions & 2 deletions polyfill/lib/duration.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -562,15 +562,15 @@ export class Duration {
}
toJSON() {
if (!ES.IsTemporalDuration(this)) throw new TypeError('invalid receiver');
return ES.TemporalDurationToString(this);
return ES.TemporalDurationToString(this, 'auto');
}
toLocaleString(locales = undefined, options = undefined) {
if (!ES.IsTemporalDuration(this)) throw new TypeError('invalid receiver');
if (typeof Intl !== 'undefined' && typeof Intl.DurationFormat !== 'undefined') {
return new Intl.DurationFormat(locales, options).format(this);
}
console.warn('Temporal.Duration.prototype.toLocaleString() requires Intl.DurationFormat.');
return ES.TemporalDurationToString(this);
return ES.TemporalDurationToString(this, 'auto');
}
valueOf() {
throw new TypeError('use compare() to compare Temporal.Duration');
Expand Down
6 changes: 6 additions & 0 deletions polyfill/test/duration.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -327,6 +327,12 @@ describe('Duration', () => {
[{}, () => {}, undefined].forEach((options) => equal(d1.toString(options), 'PT15H23M'));
});
});
describe('toJSON()', () => {
it('is like toString but always with auto precision', () => {
const d = Duration.from({ hours: 1 });
equal(d.toJSON(), d.toString({ fractionalSecondDigits: 'auto' }));
});
});
describe('toLocaleString()', () => {
it('produces an implementation-defined string', () => {
const duration = Duration.from({ hours: 12, minutes: 30 });
Expand Down

0 comments on commit 3b9e891

Please sign in to comment.