Skip to content

Instantly share code, notes, and snippets.

@shyndman
Last active November 4, 2025 21:48
Show Gist options
  • Select an option

  • Save shyndman/e0de419a730cf9298fa6641624dca84c to your computer and use it in GitHub Desktop.

Select an option

Save shyndman/e0de419a730cf9298fa6641624dca84c to your computer and use it in GitHub Desktop.
Splitting code and multiline comments
interface Chunk {
type: "code" | "comment";
content: string;
}
function* splitCodeAndComments(code: string): Generator<Chunk> {
let startIndex = 0;
while (startIndex < code.length) {
const multiLineCommentStartIndex = code.indexOf("/*", startIndex);
if (multiLineCommentStartIndex === -1) {
// No more comments, yield remaining code and exit loop
yield {type: "code", content: code.substring(startIndex)};
startIndex = code.length;
} else {
// Yield code before comment (if any)
if (multiLineCommentStartIndex > startIndex) {
yield {type: "code", content: code.substring(startIndex, multiLineCommentStartIndex)};
}
// Find comment end
const multiLineCommentEndIndex = code.indexOf("*/", multiLineCommentStartIndex + 2);
if (multiLineCommentEndIndex === -1) {
throw new Error("Unterminated multi-line comment");
}
// Yield comment
yield {type: "comment", content: code.substring(multiLineCommentStartIndex, multiLineCommentEndIndex + 2)};
startIndex = multiLineCommentEndIndex + 2;
}
}
}
for (const {type, content} of splitCodeAndComments("const a = 5; /* This is a comment */ const b = 10; /* Another comment */")) {
console.log(`[${type}]: ${content}`);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment