Skip to content

Commit 700dd41

Browse files
committed
refactor(getParts): explicit parts
less branches to account for handle Date & DateTime Regex with nullish coalescing early return on errors
1 parent a22985e commit 700dd41

File tree

1 file changed

+24
-22
lines changed

1 file changed

+24
-22
lines changed

parse.js

Lines changed: 24 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -26,37 +26,39 @@ export class IsoDateParts {
2626
};
2727
}
2828

29-
static getByDateTime(match) {
30-
let offset = this.getTimezoneOffset(match[8]);
29+
static getByDateTime(
30+
_, // full match
31+
year = "",
32+
month = "0", // 0-indexed default
33+
day = "1", // 1-indexed default
34+
hours = "0",
35+
minutes = "0",
36+
seconds = "0",
37+
milliseconds = "0",
38+
timezone = "Z",
39+
) {
40+
let offset = this.getTimezoneOffset(timezone);
3141

3242
return {
33-
year: parseInt(match[1], 10),
34-
month: match[2] ? parseInt(match[2], 10) - 1 : 0,
35-
day: match[3] ? parseInt(match[3], 10) : 1, // 1-indexed default
36-
hours: (match[4] ? parseInt(match[4], 10) : 0) - offset.hours,
37-
minutes: (match[5] ? parseInt(match[5], 10) : 0) - offset.minutes,
38-
seconds: match[6] ? parseInt(match[6], 10) : 0,
43+
year: parseInt(year, 10),
44+
month: parseInt(month, 10) - 1,
45+
day: parseInt(day, 10) ,
46+
hours: parseInt(hours, 10) - offset.hours,
47+
minutes: parseInt(minutes, 10) - offset.minutes,
48+
seconds: parseInt(seconds, 10),
3949
// may include extra precision but we only count the first 3 digits for milliseconds
40-
milliseconds: match[7] ? parseInt(match[7].slice(0, 3), 10) : 0,
50+
milliseconds: parseInt(milliseconds.slice(0, 3), 10),
4151
};
4252
}
4353

44-
static getParts(str) {
45-
let dateMatch = str.match(this.FULL_DATE_REGEX);
46-
if(dateMatch) {
47-
return this.getByDateTime(dateMatch);
48-
}
49-
50-
let dateTimeMatch = str.match(this.DATETIME_REGEX);
51-
if(dateTimeMatch) {
52-
if(dateTimeMatch[4]?.match(this.IS_FRACTIONAL_REGEX) || dateTimeMatch[5]?.match(this.IS_FRACTIONAL_REGEX)) {
54+
static getParts(str = "") {
55+
let dateTimeMatch = str.match(this.FULL_DATE_REGEX) ?? str.match(this.DATETIME_REGEX);
56+
if(!dateTimeMatch) throw new Error(`Unsupported date format: ${str}`);
57+
if(dateTimeMatch[4]?.match(this.IS_FRACTIONAL_REGEX) || dateTimeMatch[5]?.match(this.IS_FRACTIONAL_REGEX)) {
5358
throw new Error(`Unsupported date format (fractional hours or minutes): ${str}`);
54-
}
55-
56-
return this.getByDateTime(dateTimeMatch);
5759
}
5860

59-
throw new Error(`Unsupported date format: ${str}`);
61+
return this.getByDateTime(...dateTimeMatch);
6062
}
6163
}
6264

0 commit comments

Comments
 (0)