Skip to content

Commit

Permalink
printSourceLocation: simplifying by using padStart (#2981)
Browse files Browse the repository at this point in the history
  • Loading branch information
IvanGoncharov committed Mar 23, 2021
1 parent 9110135 commit a50dbd2
Showing 1 changed file with 10 additions and 21 deletions.
31 changes: 10 additions & 21 deletions src/language/printLocation.js
Expand Up @@ -21,7 +21,7 @@ export function printSourceLocation(
sourceLocation: SourceLocation,
): string {
const firstLineColumnOffset = source.locationOffset.column - 1;
const body = whitespace(firstLineColumnOffset) + source.body;
const body = ''.padStart(firstLineColumnOffset) + source.body;

const lineIndex = sourceLocation.line - 1;
const lineOffset = source.locationOffset.line - 1;
Expand All @@ -46,10 +46,10 @@ export function printSourceLocation(
return (
locationStr +
printPrefixedLines([
[`${lineNum}`, subLines[0]],
...subLines.slice(1, subLineIndex + 1).map((subLine) => ['', subLine]),
[' ', whitespace(subLineColumnNum - 1) + '^'],
['', subLines[subLineIndex + 1]],
[`${lineNum} |`, subLines[0]],
...subLines.slice(1, subLineIndex + 1).map((subLine) => ['|', subLine]),
['|', '^'.padStart(subLineColumnNum)],
['|', subLines[subLineIndex + 1]],
])
);
}
Expand All @@ -58,10 +58,10 @@ export function printSourceLocation(
locationStr +
printPrefixedLines([
// Lines specified like this: ["prefix", "string"],
[`${lineNum - 1}`, lines[lineIndex - 1]],
[`${lineNum}`, locationLine],
['', whitespace(columnNum - 1) + '^'],
[`${lineNum + 1}`, lines[lineIndex + 1]],
[`${lineNum - 1} |`, lines[lineIndex - 1]],
[`${lineNum} |`, locationLine],
['|', '^'.padStart(columnNum)],
[`${lineNum + 1} |`, lines[lineIndex + 1]],
])
);
}
Expand All @@ -71,17 +71,6 @@ function printPrefixedLines(lines: $ReadOnlyArray<[string, string]>): string {

const padLen = Math.max(...existingLines.map(([prefix]) => prefix.length));
return existingLines
.map(
([prefix, line]) =>
leftPad(padLen, prefix) + (line ? ' | ' + line : ' |'),
)
.map(([prefix, line]) => prefix.padStart(padLen) + (line ? ' ' + line : ''))
.join('\n');
}

function whitespace(len: number): string {
return Array(len + 1).join(' ');
}

function leftPad(len: number, str: string): string {
return whitespace(len - str.length) + str;
}

0 comments on commit a50dbd2

Please sign in to comment.