コメント除去

function removeComments(code) {
  const lines = code.split(/(?<=:)/g);
  const result = [];
  let inMultilineComment = false;
  let inLiteralDoubleQuote = false;
  let inLiteralSingleQuote = false;

  for (const line of lines) {
    let processedLine = '';
    let inComment = false;

    for (let i = 0; i < line.length; i++) {
      const char = line[i];

      if (inMultilineComment) {
        // マルチラインコメントモード
        if (char === '*' && line[i + 1] === '/') {
          // 終端検出
          inMultilineComment = false;
          i++; // /ぶんをスキップ
        } else if (char === '\n') {
          // コメント継続中は改行コードのみ行末に追加
          processedLine += char;
        }
      } else if (inComment) {
        // シングルラインコメントモード
        if (char === '\n') {
          processedLine += char;
          inComment = false;
        }
      } else if (inLiteralDoubleQuote) {
        processedLine += char;
        if (char === '"' && ((i == 0) || line[i - 1] !== '\\')) {
          inLiteralDoubleQuote = false;
        }
      } else if (inLiteralSingleQuote) {
        processedLine += char;
        if (char === "'" && ((i == 0) || line[i - 1] !== '\\')) {
          inLiteralSingleQuote = false;
        }
      } else {
        if (char === '/' && line[i + 1] === '/') {
          inComment = true;
          i++;
        } else if (char === '/' && line[i + 1] === '*') {
          inMultilineComment = true;
          i++;
        } else if (char === '"') {
          inLiteralDoubleQuote = true;
          processedLine += char;
        } else if (char === "'") {
          inLiteralSingleQuote = true;
          processedLine += char;
        } else {
          processedLine += char;
        }
      }
    }

    if (processedLine.length > 0 || inMultilineComment) {
      result.push(processedLine);
    }
  }

  return result.join('\n');
}

const fs = require('fs');
const path = require('path');

function main() {
  // 処理対象のファイルパスを指定
  const filePath = path.join(__dirname, 'example.js');

  // ファイルを読み込む
  const code = fs.readFileSync(filePath, 'utf8');
  const code_linux = code.replace(/\r\n/g, '\n');
  //console.log(code_linux);

  // コメントを削除
  const codeWithoutComments = removeComments(code_linux);

  // 結果を出力
  console.log(codeWithoutComments);
}

main();