From 559a212e767e5d84f8a480ef74f6a3cb274b0f32 Mon Sep 17 00:00:00 2001 From: Take Weiland Date: Tue, 22 Aug 2023 21:53:56 +0200 Subject: [PATCH] Handle invalid Durations in toHuman and toMillis (#1489) --- src/duration.js | 6 +++++- test/duration/invalid.test.js | 20 ++++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/src/duration.js b/src/duration.js index 49033a470..56cf194b1 100644 --- a/src/duration.js +++ b/src/duration.js @@ -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]; @@ -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"]; } } diff --git a/test/duration/invalid.test.js b/test/duration/invalid.test.js index 98f5e9204..ffde586a8 100644 --- a/test/duration/invalid.test.js +++ b/test/duration/invalid.test.js @@ -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"); +});