Skip to content

Instantly share code, notes, and snippets.

@undergroundwires
Created November 2, 2021 19:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save undergroundwires/bad5796bfa312e6671620401abe14283 to your computer and use it in GitHub Desktop.
Save undergroundwires/bad5796bfa312e6671620401abe14283 to your computer and use it in GitHub Desktop.
inline-comments-stackoverflow.ts
function replaceHashComment(line: string): string {
const makeInlineComment = (comment: string) => {
const value = comment?.trim();
if (!value) {
return '<##>';
}
return `<# ${value} #>`;
};
const parts = line.split('#');
if (parts.length === 1) { // No hash
return line;
} else if (parts.length === 2) {
const code = parts[0];
return code + makeInlineComment(parts[1]);
} else {
const firstDashIndex = parts[0].length;
if (firstDashIndex === 0) { // Starts with dash
return makeInlineComment(parts[1]);
}
// Do not inline if it's inline comment
const characterBeforeDash = line[firstDashIndex - 1];
if (characterBeforeDash === '<') {
for (let i = 1; i < parts.length; i++) {
const characterAfterNextDash = parts[i][0];
if (characterAfterNextDash === '>') {
return line;
}
}
}
const textAfterFirstDash = line.substring(firstDashIndex + 1);
return parts[0] + makeInlineComment(textAfterFirstDash);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment