42 lines
1.1 KiB
TypeScript
42 lines
1.1 KiB
TypeScript
function isTextInFormat(text: string) {
|
|
const lines = text
|
|
.split('\n')
|
|
.map((l) => l.trim())
|
|
.filter((l) => l !== '');
|
|
if (lines.length < 3) return false;
|
|
|
|
const date = lines[1];
|
|
const productCode = lines[2];
|
|
|
|
const dateRegex = /\d{1,2}\/\d{1,2}\/\d{4},?\s+\d{1,2}:\d{2}\s[AP]M/;
|
|
const productCodeRegex = /.+/; // ít nhất 1 ký tự
|
|
|
|
return dateRegex.test(date) && productCodeRegex.test(productCode);
|
|
}
|
|
|
|
/**
|
|
* Chuẩn hoá text: gộp nhiều dòng trống liên tiếp thành 1 dòng trống duy nhất
|
|
*/
|
|
export function normalizeBlankLines(text: string): string {
|
|
return text.replace(/\n\s*\n+/g, '\n\n');
|
|
}
|
|
|
|
export function formatTextIfValid(text: string) {
|
|
if (!isTextInFormat(text)) {
|
|
const newText = normalizeBlankLines(text);
|
|
|
|
return newText;
|
|
} // Không đúng format thì trả về nguyên bản
|
|
|
|
const lines = text
|
|
.split('\n')
|
|
.map((l) => l.trim())
|
|
.filter((l) => l !== '');
|
|
const name = lines[0];
|
|
const date = lines[1];
|
|
const productCode = lines[2];
|
|
const rest = lines.slice(3).join('\n');
|
|
|
|
return `${name} -- ${date}\n${productCode}\n\n${rest}`;
|
|
}
|