Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

printSourceLocation: simplifying by using padStart #2981

Merged
merged 1 commit into from Mar 23, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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;
}