Created
November 2, 2021 19:45
-
-
Save undergroundwires/bad5796bfa312e6671620401abe14283 to your computer and use it in GitHub Desktop.
inline-comments-stackoverflow.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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