Guest User

inline-comments-stackoverflow.ts

a guest
Nov 3rd, 2021
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function replaceHashComment(line: string): string {
  2.     const makeInlineComment = (comment: string) => {
  3.         const value = comment?.trim();
  4.         if (!value) {
  5.             return '<##>';
  6.         }
  7.         return `<# ${value} #>`;
  8.     };
  9.     const parts = line.split('#');
  10.     if (parts.length === 1) { // No hash
  11.         return line;
  12.     } else  if (parts.length === 2) {
  13.         const code = parts[0];
  14.         return code + makeInlineComment(parts[1]);
  15.     } else {
  16.         const firstDashIndex = parts[0].length;
  17.         if (firstDashIndex === 0) { // Starts with dash
  18.             return makeInlineComment(parts[1]);
  19.         }
  20.         // Do not inline if it's inline comment
  21.         const characterBeforeDash = line[firstDashIndex - 1];
  22.         if (characterBeforeDash === '<') {
  23.             for (let i = 1; i < parts.length; i++) {
  24.                 const characterAfterNextDash = parts[i][0];
  25.                 if (characterAfterNextDash === '>') {
  26.                     return line;
  27.                 }
  28.             }
  29.         }
  30.         const textAfterFirstDash = line.substring(firstDashIndex + 1);
  31.         return parts[0] + makeInlineComment(textAfterFirstDash);
  32.     }
  33. }
Advertisement
Add Comment
Please, Sign In to add comment