Skip to content

Commit

Permalink
Handle invalid Durations in toHuman and toMillis (#1489)
Browse files Browse the repository at this point in the history
  • Loading branch information
diesieben07 authored Aug 22, 2023
1 parent bc43bbc commit 559a212
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
6 changes: 5 additions & 1 deletion src/duration.js
Original file line number Diff line number Diff line change
Expand Up @@ -462,6 +462,8 @@ export default class Duration {
* ```
*/
toHuman(opts = {}) {
if (!this.isValid) return INVALID;

const l = orderedUnits
.map((unit) => {
const val = this.values[unit];
Expand Down Expand Up @@ -576,9 +578,11 @@ export default class Duration {
* @return {number}
*/
toMillis() {
if (!this.isValid) return NaN;

let sum = this.values.milliseconds ?? 0;
for (let unit of reverseUnits.slice(1)) {
if (this.values?.[unit]) {
if (this.values[unit]) {
sum += this.values[unit] * this.matrix[unit]["milliseconds"];
}
}
Expand Down
20 changes: 20 additions & 0 deletions test/duration/invalid.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,23 @@ test("Diffing invalid DateTimes creates invalid Durations", () => {
test("Duration.invalid produces invalid Intervals", () => {
expect(Duration.invalid("because").isValid).toBe(false);
});

test("Duration.toMillis produces NaN on invalid Durations", () => {
expect(Duration.invalid("because").toMillis()).toBe(NaN);
});

test("Duration.as produces NaN on invalid Durations", () => {
expect(Duration.invalid("because").as("seconds")).toBe(NaN);
});

test("Duration.toHuman produces null on invalid Durations", () => {
expect(Duration.invalid("because").toHuman()).toBe("Invalid Duration");
});

test("Duration.toISO produces null on invalid Durations", () => {
expect(Duration.invalid("because").toISO()).toBeNull();
});

test("Duration.toFormat produces Invalid Duration on invalid Durations", () => {
expect(Duration.invalid("because").toFormat("s")).toBe("Invalid Duration");
});

0 comments on commit 559a212

Please sign in to comment.