Skip to content

Commit

Permalink
refactor(kit): corrected review issues
Browse files Browse the repository at this point in the history
  • Loading branch information
Andrey Belokopytov committed Nov 1, 2024
1 parent c7ae6b8 commit 68bbca7
Showing 1 changed file with 29 additions and 36 deletions.
65 changes: 29 additions & 36 deletions projects/kit/src/lib/processors/normalize-date-preprocessor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,52 +14,45 @@ export function normalizeDatePreprocessor({
dateTimeSeparator?: string;
}): MaskitoPreprocessor {
return ({elementState, data}) => {
const dateSegments = data.split(/\D/).filter(Boolean);
const dateTimeSegments = data.split(/\D/).filter(Boolean);
const templateSegments = dateModeTemplate.split(dateSegmentsSeparator);
const includesTime = data.includes(dateTimeSeparator);

let newData = data;
const dates: string[] = [];
let dateParts: string[] = [];
const timeParts: string[] = [];
const dateSegments = dateTimeSegments.slice(
0,
includesTime ? templateSegments.length : Infinity,
);

for (let index = 0; index < dateSegments.length; index++) {
const segment = dateSegments[index]!;
const timeSegments = dateTimeSegments.slice(
includesTime ? templateSegments.length : Infinity,
);

if (!dateSegments.length || dateSegments.length % templateSegments.length !== 0) {
return {elementState, data};
}

const dates = dateSegments.reduce<string[]>((dates, segment, index) => {
const template = templateSegments[index % templateSegments.length];
const isLastTemplateSegment =
const dateIndex = Math.trunc(index / templateSegments.length);
const isLastDateSegment =
index % templateSegments.length === templateSegments.length - 1;

if (index >= templateSegments.length && includesTime) {
timeParts.push(segment);
continue;
if (!dates[dateIndex]) {
dates[dateIndex] = '';
}

if (template) {
if (isLastTemplateSegment) {
dateParts.push(segment);
dates.push(dateParts.join(dateSegmentsSeparator));
dateParts = [];
} else {
dateParts.push(normalizeDateSegment(segment, template));
}
}
}
dates[dateIndex] += isLastDateSegment
? segment
: `${segment.padStart(template?.length ?? 0, '0')}${dateSegmentsSeparator}`;

if (dates.length > 0 && dateParts.length === 0) {
if (timeParts.length > 0) {
newData = `${dates[0]}${dateTimeSeparator}${timeParts.join(':')}`;
} else {
newData = dates.join(rangeSeparator);
}
}
return dates;
}, []);

return {elementState, data: newData};
return {
elementState,
data: includesTime
? `${dates[0]}${dateTimeSeparator}${timeSegments.join(':')}`
: dates.join(rangeSeparator),
};
};
}

function normalizeDateSegment(
dateSegment: string,
templateSegment: string | undefined,
): string {
return dateSegment.padStart(templateSegment?.length ?? 0, '0');
}

0 comments on commit 68bbca7

Please sign in to comment.