Skip to content

Commit 028fde7

Browse files
authored
Merge pull request #5 from mxdvl/refactor-parts-extraction
Refactor `getByDateTime` & `getParts` with explicit arguments
2 parents c81904c + 5e64065 commit 028fde7

File tree

1 file changed

+26
-22
lines changed

1 file changed

+26
-22
lines changed

parse.js

Lines changed: 26 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -15,37 +15,41 @@ export class IsoDateParts {
1515
};
1616
}
1717

18-
static getByDateTime(match) {
19-
let offset = this.getTimezoneOffset(match[8]);
18+
static getByDateTime(
19+
_, // full match
20+
year = "",
21+
month = "0", // 0-indexed default
22+
day = "1", // 1-indexed default
23+
hours = "0",
24+
minutes = "0",
25+
seconds = "0",
26+
milliseconds = "0",
27+
timezone = "Z",
28+
) {
29+
let offset = this.getTimezoneOffset(timezone);
2030

2131
return {
22-
year: parseInt(match[1], 10),
23-
month: match[2] ? parseInt(match[2], 10) - 1 : 0,
24-
day: match[3] ? parseInt(match[3], 10) : 1, // 1-indexed default
25-
hours: (match[4] ? parseInt(match[4], 10) : 0) - offset.hours,
26-
minutes: (match[5] ? parseInt(match[5], 10) : 0) - offset.minutes,
27-
seconds: match[6] ? parseInt(match[6], 10) : 0,
32+
year: parseInt(year, 10),
33+
month: parseInt(month, 10) - 1,
34+
day: parseInt(day, 10),
35+
hours: parseInt(hours, 10) - offset.hours,
36+
minutes: parseInt(minutes, 10) - offset.minutes,
37+
seconds: parseInt(seconds, 10),
2838
// may include extra precision but we only count the first 3 digits for milliseconds
29-
milliseconds: match[7] ? parseInt(match[7].slice(0, 3), 10) : 0,
39+
milliseconds: parseInt(milliseconds.slice(0, 3), 10),
3040
};
3141
}
3242

33-
static getParts(str) {
34-
let dateMatch = str.match(this.FULL_DATE_REGEX);
35-
if(dateMatch) {
36-
return this.getByDateTime(dateMatch);
43+
static getParts(str = "") {
44+
let dateTimeMatch = str.match(this.FULL_DATE_REGEX) ?? str.match(this.DATETIME_REGEX);
45+
if(!dateTimeMatch) {
46+
throw new Error(`Unsupported date format: ${str}`);
3747
}
38-
39-
let dateTimeMatch = str.match(this.DATETIME_REGEX);
40-
if(dateTimeMatch) {
41-
if(dateTimeMatch[4]?.match(this.IS_FRACTIONAL_REGEX) || dateTimeMatch[5]?.match(this.IS_FRACTIONAL_REGEX)) {
42-
throw new Error(`Unsupported date format (fractional hours or minutes): ${str}`);
43-
}
44-
45-
return this.getByDateTime(dateTimeMatch);
48+
if(dateTimeMatch.slice(4,6).some(part => !!part?.match(this.IS_FRACTIONAL_REGEX))) {
49+
throw new Error(`Unsupported date format (fractional hours or minutes): ${str}`);
4650
}
4751

48-
throw new Error(`Unsupported date format: ${str}`);
52+
return this.getByDateTime(...dateTimeMatch);
4953
}
5054
}
5155

0 commit comments

Comments
 (0)