Skip to content

Commit 60126db

Browse files
committed
Rewrite complex logic into simpler indentComma function
1 parent c9b5ac7 commit 60126db

File tree

1 file changed

+10
-13
lines changed

1 file changed

+10
-13
lines changed

src/formatter/formatCommaPositions.ts

Lines changed: 10 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -64,25 +64,22 @@ function groupCommaDelimitedLines(lines: string[]): string[][] {
6464
// makes all lines the same length by appending spaces before comma
6565
function formatTabular(commaLines: string[]): string[] {
6666
const commaLinesWithoutComments = commaLines.map(line => line.replace(/--.*/, ''));
67-
const maxLineLength = maxLength(commaLinesWithoutComments);
68-
return trimTrailingCommas(commaLines).map((line, i) => {
67+
const commaPosition = maxLength(commaLinesWithoutComments) - 1;
68+
return commaLines.map((line, i) => {
6969
if (i === commaLines.length - 1) {
7070
return line; // do not add comma for last item
7171
}
72-
// find comment match in string
73-
const commentMatch = /\s*--/.exec(line);
74-
// if comment found, get its start index to slice string by it
75-
// if comment not found, get line.length so slice will return whole line
76-
const endOfContentWithoutCommentPosition = commentMatch ? commentMatch.index : line.length;
77-
const lineContentWithoutComment = line.slice(0, endOfContentWithoutCommentPosition).trimEnd();
78-
const spaces = ' '.repeat(maxLineLength - lineContentWithoutComment.length - 1);
79-
const comment = line.slice(endOfContentWithoutCommentPosition + 1);
80-
81-
// trim end will handle case without comment
82-
return `${lineContentWithoutComment}${spaces}, ${comment}`.trimEnd();
72+
return indentComma(line, commaPosition);
8373
});
8474
}
8575

76+
function indentComma(line: string, commaPosition: number) {
77+
const [, code, comment] = line.match(/^(.*?),(\s*--.*)?$/) || [];
78+
79+
const spaces = ' '.repeat(commaPosition - code.length);
80+
return `${code}${spaces},${comment ?? ''}`;
81+
}
82+
8683
function formatBefore(commaLines: string[], indent: string): string[] {
8784
return trimTrailingCommas(commaLines).map((line, i) => {
8885
if (i === 0) {

0 commit comments

Comments
 (0)